experimental::optional nullopt_t 构造函数

experimental::optional nullopt_t constructor

Here 描述了 nullopt_tnullopt 为 c++ 提议的 optional 对象:

struct nullopt_t{see below}; 
constexpr nullopt_t nullopt(unspecified);

[...] Type nullopt_t shall not have a default constructor. It shall be a literal type. Constant nullopt shall be initialized with an argument of literal type.

文档的 The op = {} syntax 章节解释了这样做的原因:为了使 op = {} 明确无误,必须采用一些技巧,其中之一是 nullopt_t不能默认构造。

我的问题是这里的文字类型是什么意思?我找到了这个 SO post。所以在我看来,只需要另一个空的 class 就可以了。它也可以是采用 int 的构造函数吗?

最符合要求的 nullopt_t class 是什么样的?

像这样:

struct nullopt_t_construct_tag_t{};

struct nullopt_t {
  nullopt_t() = delete; // I know declaring it as deleted is redundant
  constexpr nullopt_t(nullopt_t_construct_tag_t) {};
};

constexpr nullopt_t nullopt(nullopt_t_construct_tag_t{});

或者这个:

struct nullopt_t {
  nullopt_t() = delete;
  constexpr nullopt_t(int) {};
};

constexpr nullopt_t nullopt(0);

一个最小的实现是

struct nullopt_t {
    constexpr nullopt_t(int) {}
};

不会隐式声明默认构造函数,[class.ctor]/4:

If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4).

... 和 nullopt_t 可以从 int 构造,文字类型。
请注意,在您的代码中存在一个默认构造函数,尽管它被定义为已删除。

以上定义确实满足文字类型的要求:

A type is a literal type if it is:
(10.5) — a class type (Clause 9) that has all of the following properties:

  • it has a trivial destructor,
  • it is an aggregate type (8.5.1) or has at least one constexpr constructor [..] that is not a copy or move constructor, and
  • all of its non-static data members and base classes are of non-volatile literal types.