C++ Logo

std-proposals

Advanced search

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

From: Sebastian Wittmeier <wittmeier_at_[hidden]>
Date: Wed, 21 May 2025 10:23:32 +0200
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_at_[hidden]> 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_at_[hidden]; CC:Frederick Virchanza Gotham <cauldwell.thomas_at_[hidden]>; 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_at_[hidden] https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals

Received on 2025-05-21 08:31:01