Alternative:

 

auto a = AllInUniversial() ? 42 : std::nullopt;

// type of a is std::variant<int, std::nullopt_t>;


std::optional<int> r = a;
// assigns int or std::nullopt

 


 

-----Ursprüngliche Nachricht-----
Von: Frederick Virchanza Gotham via Std-Proposals <std-proposals@lists.isocpp.org>
Gesendet: Mi 21.05.2025 10:25
Betreff: Re: [std-proposals] Hope that std::optional and comma expressions can work this way
An: std-proposals@lists.isocpp.org;
CC: Frederick Virchanza Gotham <cauldwell.thomas@gmail.com>;
On Wed, May 21, 2025 at 9:12 AM Simon W wrote:
>
> The comma expression requires that the expressions on both sides of the colon are of the same type.  But I think this syntax should be accepted:
>
> bool AllInUniversial();
>
> std::optional<int> r = AllInUniversial() ? 42 : std::nullopt;


Looking at that ternary operator, it has three operands.

   Operand No. 1 is a PRvalue of type bool.
   Operand No. 2 is a PRvalue of type int.
   Operand No. 3 is an Lvalue of type std::nullopt_t

So when the compiler encounters the following line of code:

   std::optional<int> r = AllInUniversial() ? 42 : std::nullopt;

The quickest solution here is:

   std::optional<int> r = AllInUniversal() ? std::optional<int>(42) :
std::optional<int>(std::nullopt);

But were you hoping that it would be turned into something like the
following under the hood?

   typedef std::optional<int> T;
   alignas(T) char unsigned storage[sizeof(T)];
   T &r = *static_cast<T*>(static_cast<void*>(&storage));
   if ( AllInUniversal() ) std::construct_at(&r, 42          );
   /****************/ else std::construct_at(&r, std::nullopt);
--
Std-Proposals mailing list
Std-Proposals@lists.isocpp.org
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals