如果constexpr()在C++ 17中给出错误

msc*_*msc 0 c++ constexpr c++17 if-constexpr

constexpr在C++ 17中使用此参考链接阅读了该文章.

然后,我制作了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;
}
Run Code Online (Sandbox Code Playgroud)

但是,编译器会出错:

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;
Run Code Online (Sandbox Code Playgroud)

为什么会出错?

das*_*ght 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;
}
Run Code Online (Sandbox Code Playgroud)

编译器知道i编译时的值,因此根据其值,三个分支中只有一个将保留在已编译的代码中.

  • @ tobi303有这个原因的部分原因是我们实际上可以编写像`if constexpr(std :: is_same_v <int,T>)`这样的代码,它实际上可以工作而不必使用SFINAE.请参阅此示例:http://coliru.stacked-crooked.com/a/4fd12ae025b3ac0c (2认同)

max*_*x66 5

if constexpr ( condition )工作编译时,所以condition必须是可评估的编译时间.

int i = 0不是常量变量,因此i == 0不可评估编译时间.

尝试使用int const i = 0或更好的constexpr int i = 0.