Here描述了 nullopt_t
和 nullopt
用于为 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 .所以在我看来,只需要另一个空类就可以了。它也可以是采用 int
的构造函数吗?
最小的符合要求的 nullopt_t
类应该是什么样的?
像这样:
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.
关于c++ - experimental::optional nullopt_t 构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28332078/