gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 14:40:55 24 4
gpt4 key购买 nike

我已经阅读了有关使用此 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;

为什么报错?

最佳答案

你误解了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 的值,因此根据它的值,三个分支中只有一个会保留在编译后的代码中。

关于c++ - 如果 constexpr() 在 C++17 中给出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46174818/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com