c++ optional_t 类型标签 (n3527)
c++ optional_t type tag (n3527)
n3527建议在c++中加入std::optional<T>
。作为它的一部分,它定义了 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, which expounds on the extra complexity of nullopt_t
in The op = {} syntax 段落。
简而言之,nullopt_t
以这种方式声明,使其成为非 DefaultConstructible
,以避免 op = {}
语法的歧义。您可以阅读前面链接的段落以了解更多详细信息。
n3527建议在c++中加入std::optional<T>
。作为它的一部分,它定义了 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, which expounds on the extra complexity of nullopt_t
in The op = {} syntax 段落。
简而言之,nullopt_t
以这种方式声明,使其成为非 DefaultConstructible
,以避免 op = {}
语法的歧义。您可以阅读前面链接的段落以了解更多详细信息。