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

拟墨画扇 提交于 2020-07-30 06:59:09

问题


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?


回答1:


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



回答2:


C++ reference says it all:

std::nullopt_t is an empty class type used to indicate optional type with uninitialized state. In particular, std::optional has a constructor with nullopt_t as a single argument, which creates an optional that does not contain a value.

std::nullopt_t



来源:https://stackoverflow.com/questions/49617785/why-is-stdnullopt-t-part-of-the-c-standard

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!