Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is std::nullopt_t part of the C++ standard?

Tags:

c++

c++17

I don't understand the reasoning for the inclusion of std::nullopt_t in the standard. Does it exist strictly for convenience, or is it required in some niche circumstances?

To be clear, I understand that it is used as an argument to construct empty std::optional objects. But considering a default constructor for std::optional already exists, there seems to be no obvious motivation for the existence of std::nullopt_t. Must such a constructor and assignment operator exist for std::optional to conform to a particular concept? If so, which concept?

like image 508
Zark Bardoo Avatar asked Apr 02 '18 19:04

Zark Bardoo


2 Answers

nullopt_t is the type of nullopt which indicates disengaged optional state. nullopt allows disambiguating overloads such as (example from the optional proposal):

void run(complex<double> v);
void run(optional<string> v);

run(nullopt);              // pick the second overload
run({});                   // ambiguous
like image 175
eerorika Avatar answered Sep 27 '22 23:09

eerorika


Here is another example I just ran into:

// GCC: error: expected primary-expression before '{' token
// Clang: error: initializer list cannot be used on the right hand side of operator ':'
std::optional<int> x = some_condition ? std::optional(0) : {}; 

// works
std::optional<int> y = some_condition ? std::optional(0) : std::nullopt;
like image 24
Alexey Romanov Avatar answered Sep 27 '22 22:09

Alexey Romanov