我使用此reference链接了解了C ++ 17中的constexpr
。
然后,我制作了C ++程序来测试constexpr
:
#include <iostream>
int i = 10;
int func()
{
if constexpr (i == 0)
return 0;
else if (i > 0)
return i;
else
return -1;
}
int main()
{
int ret = func();
std::cout<<"Ret : "<<ret<<std::endl;
}
但是,编译器会出错:
main.cpp: In function 'int func()':
main.cpp:8:25: error: the value of 'i' is not usable in a constant expression
if constexpr (i == 0)
^
main.cpp:4:5: note: 'int i' is not const
int i = 10;
为什么会出错?
答案 0 :(得分:7)
你误解了if constexpr
的含义。这不是对在运行时执行的const表达式的测试,它是对在编译时执行的逻辑表达式的测试。
该构造大致类似于预处理器的#if
,因为其他分支被删除,以及可能无法编译的代码。
这将有效:
template<int i>
int func()
{
if constexpr (i == 0)
return 0;
else if constexpr (i > 0)
return i;
else
return -1;
}
编译器在编译时知道i
的值,因此根据其值,只有三个分支中的一个将保留在已编译的代码中。
答案 1 :(得分:5)
if constexpr ( condition )
适用于编译时,因此condition
必须是可评估的编译时间。
int i = 0
不是常量变量,因此i == 0
不是可评估的编译时间。
尝试使用int const i = 0
或更好的constexpr int i = 0
。