c++ - experimental::optional nullopt_t 构造函数

标签 c++ option-type c++17

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 .所以在我看来,只需要另一个空类就可以了。它也可以是采用 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/

相关文章:

swift - 在 Swift 中默认类型推断变量是 "optionals"吗?

C++:你能做一个 lambda 隐式复制捕获加上显式复制捕获吗?

c++ - 重载一组类的加号运算符

c++ - 如何组合一些仿函数来生成 `isOdd` 函数?

c++ - std::make_from_tuple 在没有构造函数的情况下无法编译

c++ - 生成文件错误 : undefined reference to main

swift - 为什么在此示例中使用强制展开?

swift - 引用 [weak self] 作为自己? animateWithDuration 内部导致崩溃

c++ - 自定义开关功能中的大量神秘错误

c++ - 如何读取 XSD 架构元素 <xs :schema 的 'Version' 属性