对'if constexpr'的理解有误 [英] Wrong understanding of 'if constexpr'
问题描述
我有以下代码
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
-std=gnu++17
我对
if constexpr (condition)
是编译过程中的一部分
} else {
x
return num;
}
被丢弃,关于未定义的我没有错误
get discarded and I get no error about the undefined
x
我的理解是错误的,因为"if constexpr"类似于
Is my understanding wrong that this 'if constexpr' is something like
#ifdef CONDITION
return num * num;
#else
x
return num;
#endif
如何修改此代码以进行编译?
How do I modify this code that I can compile this?
感谢您的帮助
推荐答案
如何修改此代码以进行编译?
How do I modify this code that I can compile this?
要修复代码,只需用x
删除该行即可.
To fix your code, simply remove the line with x
.
我的理解是错误的,这个'if constexpr'类似于[...]
Is my understanding wrong that this 'if constexpr' is something like [...]
是的,您的理解是错误的.来自 cppreference :
Yes, your understanding is wrong. From cppreference:
在模板之外,已完全检查了丢弃的语句.
if constexpr
不能替代#if
预处理指令.
Outside a template, a discarded statement is fully checked.
if constexpr
is not a substitute for the#if
preprocessing directive.
这意味着if constexpr
块中的每个分支都必须是有效的C ++,即使它永远不会被使用.
This means every branch in an if constexpr
block must be valid C++, even if it's never going to be used.
这篇关于对'if constexpr'的理解有误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!