Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/143.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/selenium/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在构造函数中使用constexpr成员_C++_C++14_Constexpr - Fatal编程技术网

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

C++ 在构造函数中使用constexpr成员,c++,c++14,constexpr,C++,C++14,Constexpr,我有以下代码: struct C { int var = 3; }; 当我这样使用它时: constexpr C c; static_assert(c.var == 3, ""); 一切正常,但是如果我想在constexprconstructor中执行此断言,它会失败: struct C { constexpr C() { static_assert(var == 3, ""); } int var = 3; }; 为什么会这样? 在constexpr构造函数中,在

我有以下代码:

struct C {
    int var = 3;
};
当我这样使用它时:

constexpr C c;
static_assert(c.var == 3, "");
一切正常,但是如果我想在
constexpr
constructor中执行此断言,它会失败:

struct C {
    constexpr C() { static_assert(var == 3, ""); }
    int var = 3;
};
为什么会这样? 在
constexpr
构造函数中,在编译时应该知道每个变量,对吗

在constexpr构造函数中,每个变量在编译时都应该是已知的,对吗

constexpr
构造函数是一种函数(方法),可以在编译时执行(在您的例子中,声明
c
constexpr
),也可以在运行时执行(例如,声明
c2;
而不是
constexpr

因此,构造函数中的
static\u assert()
是一个错误,因为编译器在运行时执行构造函数时无法检查它

换句话说。。。 当你使用它如下

constexpr C c;
static_assert(c.var == 3, "");
可以编译,因为
c
已声明
constexpr
,因此
c.var
的值是已知的编译时

但是

给出错误,因为
c2.var的值不知道编译时

书写

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

要求在这两种情况下都执行
static\u assert()

一个
constepr
-函数,无论是ctor函数、(静态)成员函数还是自由函数,都是一个可以在编译时使用适当参数进行计算的函数

除非在需要编译时常量的上下文中执行,否则不能保证在编译时对任何特定调用进行求值。
因此,在需要编译时常量表达式的地方,不能使用任何非
静态constexpr
-成员

即使是GCC的
\uuuuu内置常量\up()
,它允许您有更多的回旋余地,出于某些原因,在这方面也没有帮助:


Hm.不完全是这样,但是你已经差不多做到了。如果var在所有情况下都是3,为什么编译器不能在编译时检查这个呢?@TaylorNichols-这是
Ron
的建议:使
var
静态constexpr
因此该值也是编译时已知的Not
constexpr
对象的值。但是如果
var
是一个变量;不是一个常数;你不能
static\u assert()
一个变量。也许值得注意的是,
这个
本身不是构造函数中的constexpr?@Aconcagua-不确定你是否理解你的问题,但是。。。我认为这是同一问题的另一个方面:
constexpr
方法(也是构造函数)中,这个
不能是
constexpr
,因为该方法也可以由非contexpr对象执行。
constexpr C() { static_assert(var == 3, ""); }