Subtle C++ Compiler Error with std::optional and the Conditional Operator -- Giovanni Dicanio

An example of writing clear code with good intention, but getting an unexpected C++ compiler error:

Subtle C++ Compiler Error with std::optional and the Conditional Operator

by Giovanni Dicanio

From the article:

I was asked: “What’s the problem here? Are there limitations of using the {} syntax to specify nothing?”

This is a good question. So, clearly, the C++ compiler didn’t interpret the {} syntax as a way to default-initialize the std::optional in case the string was not empty (i.e. the second “branch” in the conditional ternary operator).

A first step to help the C++ compiler figuring out the programmer’s intention could be to be more explicit. So, instead of using {}, you can try and use the std::nullopt constant, which represents an optional that doesn’t store any value. [...]

[...]

P.S. I’m not a C++ “language lawyer”, but it would be great if the C++ language could be extended to allow the original simple code to just work.

Add a Comment

You must sign in or register to add a comment.

Comments (0)

There are currently no comments on this entry.