C++17 make_optional constexpr-ness

标签 c++ std c++17

This pagemake_optional C++17 中的函数返回 constexpr optional<...> .我认为(虽然我可能是错的)这需要 optional<T>有一个 constexpr复制或移动构造函数。然而,this page也说不是这样的。

我不知道如何make_optional可以按照当前的 C++1z 草案实现。参见 this post为了澄清。是否有一些解决方法,或者这可能只是标准草案/cppreference 的错误?

最佳答案

感谢@Yakk 和@T.C.为了他们的解释。我觉得一个例子应该让事情更清楚:

struct wrapper {
    int value;

    // non-explicit constexpr constructor
    constexpr wrapper(int v) noexcept : value(v) {}

    // non-constexpr copy & move constructors
    wrapper(const wrapper& that) noexcept : value(that.value) {}
    wrapper(wrapper&& that) noexcept : value(that.value) {}
};

constexpr wrapper make_wrapper(int v)
{
    return {v};
}

int main()
{
    constexpr auto x = make_wrapper(123);  // error! copy/move construction,
                                           // but no constexpr copy/move ctor

    constexpr int y = make_wrapper(123).value;  // ok
    static_assert(y == 123, "");                // passed
}

因此 make_wrapper 确实成功返回了一个 constexpr wrapper;它是复制/移动构造(尽管通常被编译器省略)阻止代码编译,因为没有 constexpr 复制/移动构造函数。

我们可以通过使用其成员值初始化一个constexpr 变量来验证返回的(临时)wrapper 对象的constexpr 性。

关于C++17 make_optional constexpr-ness,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37933655/

相关文章:

c++ - 错误 C2678 : binary '!=' : no operator found

c++ - 什么是 Map 以及如何在 C++ 中使用 Map?

c++ - 在不释放内存的情况下销毁 std::vector

c++ - 如何返回标准文件流

c++ - 如何实现通用 switch/case,它也适用于一般 C++ 类型并且语法相似?

c++ - 使用 Win32/MFC 加密数据

c++ - 使用 win32 API 在 C++ 中查找和替换文件中的字符串标记

c++ - 遍历带有非类型模板参数的模板基类的CRTP继承链

c++ - 使用可变参数模板将指针传递给成员

C++ 多重继承不明确