如果条件导致错误,则在constexpr中比较constexpr函数参数 [英] Comparing constexpr function parameter in constexpr-if condition causes error
问题描述
我正在尝试比较constexpr-if语句中的函数参数.
I'm trying to compare a function parameter inside a constexpr-if statement.
这是一个简单的例子:
constexpr bool test_int(const int i) {
if constexpr(i == 5) { return true; }
else { return false; }
}
但是,当我使用带有以下标志的GCC 7进行编译时:
g++-7 -std=c++1z test.cpp -o test
我收到以下错误消息:
However, when I compile this with GCC 7 with the following flags:
g++-7 -std=c++1z test.cpp -o test
I get the following error message:
test.cpp: In function 'constexpr bool test_int(int)':
test.cpp:3:21: error: 'i' is not a constant expression
if constexpr(i == 5) { return true; }
但是,如果我将test_int
替换为其他功能:
However, if I replace test_int
with a different function:
constexpr bool test_int_no_if(const int i) { return (i == 5); }
然后,下面的代码编译没有错误:
Then the following code compiles with no errors:
int main() {
constexpr int i = 5;
static_assert(test_int_no_if(i));
return 0;
}
我不明白为什么constexpr-if版本无法编译,特别是因为static_assert可以正常工作.
I don't understand why the constexpr-if version fails to compile, especially since the static_assert works just fine.
任何对此的建议将不胜感激.
Any advice on this would be appreciated.
谢谢!
推荐答案
来自 constexpr if :
在constexpr if语句中,condition的值必须为a 上下文转换的布尔类型的常量表达式.
In a constexpr if statement, the value of condition must be a contextually converted constant expression of type bool.
然后,来自常量表达式:
定义一个可以在编译时求值的表达式.
Defines an expression that can be evaluated at compile time.
很显然,i == 5
不是常数表达式,因为i
是在运行时评估的函数参数.这就是编译器抱怨的原因.
Obviously, i == 5
is not a constant expression, because i
is a function parameter which is evaluated at run time. That is why the compiler complains.
使用功能时:
constexpr bool test_int_no_if(const int i) { return (i == 5); }
然后可能会在编译期间对其进行评估,具体取决于其参数在编译时是否已知.
then it might be evaluated during the compile time depending on whether it's parameter is known at compile time or not.
如果i
的定义如下:
constexpr int i = 5;
然后i
的值在编译期间是已知的,并且test_int_no_if
可能也在编译期间求值,从而有可能在static_assert
内部调用它.
then the value of i
is known during the compile time and test_int_no_if
might be evaluated during the compile too making it possible to call it inside static_assert
.
还请注意,将函数参数标记为const
不会使其成为编译时间常数.这只是意味着您无法在函数内部更改参数.
Also note, that marking function parameter as const
does not make it a compile time constant. It just means that you cannot change the parameter inside the function.
这篇关于如果条件导致错误,则在constexpr中比较constexpr函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!