[英]why can't use constexpr if (expression) , even the expression can be evaluated at compile time
//code1
class Test {
public:
constexpr Test(const char *p) : p_(p) {}
constexpr int foo() const
{
if(p_[0] != 'a')
return 1;
else
return 2;
}
const char *p_;
};
int arr[Test("bbb").foo()]; //this works
why the following code not work?为什么下面的代码不起作用?
//code2
constexpr int foo() const
{
constexpr if (p_[0] != 'a') //add constexpr
return 1;
else
return 2;
}
Got an error:出现错误:
error: expected unqualified-id before 'if'
错误:'if' 之前的预期不合格 ID
To my understanding, since " p_[0] != 'a'
" can be evaluated at compile time(as shown in code1), so constexpr if (p_[0] != 'a')
should be a valid statement which can be evaluate during compiling.据我了解,由于“
p_[0] != 'a'
”可以在编译时进行评估(如代码1所示),所以constexpr if (p_[0] != 'a')
应该是一个有效的语句,它可以在编译过程中进行评估。
To my understanding, since "
p_[0] != 'a'
" can be evaluated at compile time(as shown in code1), soconstexpr if (p_[0] != 'a')
should be a valid statement which can be evaluate during compiling.据我了解,由于“
p_[0] != 'a'
”可以在编译时进行评估(如代码1所示),所以constexpr if (p_[0] != 'a')
应该是一个有效的语句,它可以在编译过程中进行评估。
p_[0] != 'a'
can be evaluated compile-time but can also be evaluated run-time. p_[0] != 'a'
可以在编译时求值,但也可以在运行时求值。
The problem is that a if constexpr
test must be evaluated compile-time.问题是必须在编译时评估
if constexpr
测试。 And this is impossible when foo()
is executed run-time or when the corresponding Test
object is initialized run-time.当
foo()
在运行时执行或相应的Test
对象在运行时初始化时,这是不可能的。
So the error.所以错误。
Or better: the error if you write correctly或者更好:错误如果你写得正确
if constexpr (p_[0] != 'a')
In your case the order between if
and constexpr
is also wrong.在您的情况下,
if
和constexpr
之间的顺序也是错误的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.