我正在尝试比较 constexpr-if 语句中的函数参数。
这是一个简单的例子:
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
我收到以下错误消息:
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
:
constexpr bool test_int_no_if(const int i) { return (i == 5); }
然后下面的代码编译没有错误:
int main() {
constexpr int i = 5;
static_assert(test_int_no_if(i));
return 0;
}
我不明白为什么 constexpr-if 版本无法编译,特别是因为 static_assert 工作得很好。
如有任何建议,我们将不胜感激。
谢谢!
最佳答案
来自 constexpr if :
In a constexpr if statement, the value of condition must be a contextually converted constant expression of type bool.
然后,从constant expression :
Defines an expression that can be evaluated at compile time.
显然,i == 5
不是常量表达式,因为 i
是在运行时评估的函数参数。这就是编译器提示的原因。
当你使用函数时:
constexpr bool test_int_no_if(const int i) { return (i == 5); }
然后它可能会在编译时被评估,这取决于它的参数在编译时是否已知。
如果i
定义如下:
constexpr int i = 5;
然后是i
的值在编译期间已知并且test_int_no_if
也可能在编译期间进行评估,从而可以在 static_assert
中调用它.
另请注意,将函数参数标记为 const
不会使其成为编译时间常量。这只是意味着您不能更改函数内部的参数。
关于c++ - 在 constexpr-if 条件下比较 constexpr 函数参数导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45377244/