gpt4 book ai didi

C++17 make_optional constexpr-ness

转载 作者:可可西里 更新时间:2023-11-01 18:38:22 27 4
gpt4 key购买 nike

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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com