我有以下代码
static constexpr bool condition = true;
int square(int num) {
if constexpr (condition) {
return num * num;
} else {
x
return num;
}
}
int main() {
return square(3);
}
编译为
-std=gnu++17
我的假设
if constexpr (condition)
是编译期间的那部分
} else {
x
return num;
}
被丢弃,我没有得到关于未定义的错误
x
我的理解是否错误,这个“if constexpr”类似于
#ifdef CONDITION
return num * num;
#else
x
return num;
#endif
我如何修改这段代码以便我可以编译它?
感谢帮助
最佳答案
How do I modify this code that I can compile this?
要修复您的代码,只需删除带有 x
的行即可。
Is my understanding wrong that this 'if constexpr' is something like [...]
是的,你的理解是错误的。来自 cppreference :
Outside a template, a discarded statement is fully checked.
if constexpr
is not a substitute for the#if
preprocessing directive.
这意味着 if constexpr
block 中的每个分支都必须是有效的 C++,即使它永远不会被使用。
关于c++ - 'if constexpr'理解错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58300760/