我正在尝试编写以下形式的constexpr
函数:
constexpr int foo(bool cond) {
int a, b, c;
if (cond) {
a = 1;
b = 2;
c = 3;
}
else {
a = -1;
b = -2;
c = -3;
}
return a + b + c;
}
int a = cond ? 1 : -1;
等,但我不希望这样做。有没有办法说服编译器局部变量将被初始化?
However, the compiler complains that I am using an uninitialized variables, despite the fact that the eventual initialization of the local variables is guaranteed.
constexpr
函数,在[dcl.constexpr]中有一个要求:The definition of a
constexpr
function shall satisfy the following requirements: [...] its function-body shall be= delete
,= default
, or a compound-statement that does not contain [...] a definition of a variable of non-literal type or of static or thread storage duration or for which no initialization is performed.
constexpr
函数中不能包含未初始化的变量,a
,b
和c
适合您。a
,b
和c
初始化为零。这就绕过了这个要求。或者,您可以在a
的每个范围内初始化b
,c
和if
。或者,您可以使用另一个constexpr
函数进行求和:constexpr int f(int a, int b, int c) { return a+b+c; };
constexpr int foo(bool cond) {
if (cond) {
return f(1,2,3);
}
else {
return f(-1,-2,-3);
}
}
关于c++ - 延迟局部变量初始化的constexpr函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41509106/
欢迎光临 OGeek|极客世界-中国程序员成长平台 (https://www.ogeek.cn/) | Powered by Discuz! X3.4 |