C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Hope that std::optional and comma expressions can work this way

From: Jonathan Wakely <cxx_at_[hidden]>
Date: Wed, 21 May 2025 11:30:55 +0100
On Wed, 21 May 2025 at 09:12, Simon W via Std-Proposals
<std-proposals_at_[hidden]> wrote:
>
>
> The comma expression

I think you mean conditional expression.

> requires that the expressions on both sides of the colon are of the same type.

No, it requires that they have a common type that both can be converted to.

> But I think this syntax should be accepted:
>
> bool AllInUniversial();
>
> std::optional<int> r = AllInUniversial() ? 42 : std::nullopt;

This doesn't work because 42 isn't convertible to std::nullopt_t and
std::nullopt isn't convertible to int. The compiler doesn't check
every type in the program to determine whether there's something that
they could both be converted to (and it certainly doesn't instantiate
every possible specialization of a class template to see if that would
work).

You could write this:

auto r = cond ? 42 : std::optional<int>();
or:
auto r = cond ? std::optional(42) : std::nullopt;
Or just:
std::optional<int> r;
if (cond)
  r = 42;

Received on 2025-05-21 10:31:13