c++optional_t类型标记(n3527)

c++ optional_t type tag (n3527)

本文关键字:n3527 类型 c++optional      更新时间:2023-10-16

n3527建议将std::optional<T>添加到c++中。作为其中的一部分,它定义了nullopt_t类型标记。

gcc的(4.9)libstdc++定义optional_t如下:

struct nullopt_t
{
    enum class _Construct { _Token };
    explicit constexpr nullopt_t(_Construct) { }
};
constexpr nullopt_t nullopt { nullopt_t::_Construct::_Token };

clang的(3.6)libc++将其定义为:

struct nullopt_t
{
    explicit constexpr nullopt_t(int) noexcept {}
};
constexpr nullopt_t nullopt{0};

我的问题是:为什么要这样做,这(看起来)过于复杂了?

换句话说,为什么不能定义如下:

struct nullopt_t { };
constexpr nullopt_t nullopt { };

例如,std::defer_lock_t和其他内容就是这样在标准库中定义的。

在这里回答了我自己,但这要归功于kakkoko让我走上了正轨。

相关问题链接到一个新的修订版n3793,该修订版在op={}语法段落中阐述了nullopt_t的额外复杂性。

简而言之,为了避免op = {}语法的歧义,nullopt_t是以这种方式声明的,使其成为非DefaultConstructible。你可以阅读上面的段落了解更多的细节。