gpt4 book ai didi

c++ - 在构造函数中使用 constexpr 成员

转载 作者:太空狗 更新时间:2023-10-29 20:34:02 27 4
gpt4 key购买 nike

我有以下代码:

struct C {
int var = 3;
};

当我这样使用它时:

constexpr C c;
static_assert(c.var == 3, "");

一切正常,但是如果我想在 constexpr 构造函数中执行此断言,它会失败:

struct C {
constexpr C() { static_assert(var == 3, ""); }
int var = 3;
};

为什么会这样?在 constexpr 构造函数中,每个变量都应该在编译时已知,对吗?

最佳答案

In constexpr constructor every variable should be known at compile time, right?

错了。

A constexpr 构造函数是一个可以在编译时执行的函数(方法)(在你的例子中,声明 c constexpr)而且运行时(例如,声明 C c2; 而不是 constexpr)。

所以构造函数中的 static_assert() 是一个错误,因为编译器无法在运行时执行构造函数时检查它。

换句话说……当你按如下方式使用它时

constexpr C c;
static_assert(c.var == 3, "");

可以编译,因为 c 被声明为 constexpr,所以 c.var 的值在编译时已知。

但是

C c2;
static_assert(c2.var == 3, "");

给出错误,因为 c2.var 的值在编译时未知。

写作

constexpr C() { static_assert(var == 3, ""); }

要求在这两种情况下都执行 static_assert()

关于c++ - 在构造函数中使用 constexpr 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51406232/

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