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

标签 c++ c++14 constexpr

我有以下代码:

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/

相关文章:

c++ - 分离 C++ 模板函数的声明和定义的正确格式

使用类 T 的 C++ 函数指针

c++ - 使用派生类的静态 constexpr 数据成员初始化基类的静态 constexpr 数据成员

c++ - 从 C++14 模板特化中删除 constexpr?

c++ - 简单的平均计算

c++ - IExecuteCommand 与 IContextMenu 的多功能性

c++ - 获取右值引用的地址是什么意思?

c++ - 如何正确地从函数中给出 vector (type_traits)

C++14 在方法定义中使用 auto 关键字

c++ - 来自 static constexpr std::array 的 UTF-8 constexpr std::string_view 在 MSVC 上无效