C++ Logo

std-proposals

Advanced search

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

From: Simon Schröder <dr.simon.schroeder_at_[hidden]>
Date: Sat, 24 May 2025 17:28:53 +0200
> On May 21, 2025, at 5:29 PM, Frederick Virchanza Gotham via Std-Proposals <std-proposals_at_[hidden]> wrote:
>
>
> Obviously my code is pretty horrible -- I was trying to give an idea
> of what would happen "under the hood", so to speak. I was trying to
> show how the ternary operator might, under the hood, be turned into an
> "if - else" resulting in two separate statements to initialise the
> "optional" variable.

If you want to make it a little nicer you can use an immediately invoked lambda:
auto r = [&]() -> std::optional<int> { if(AllInUniversial()) return 42; else return std::nullopt; }();

It’s not the ternary operator, but still quite nice 😊

Received on 2025-05-24 15:29:08