constexpr decltype(auto) F(int n)
{
if consteval
{
return (int)3;
}
else
{
return (char)'c';
}
}
int main() {
int n;
cin >> n;
cout << typeid(decltype(F(4))).name() << endl;
cout << typeid(decltype(F(n))).name() << endl;
return 0;
}
错误(gcc 12.2):“自动返回类型的推导不一致:‘int’然后是‘char’”使用
if constexpr
不会给出此错误,因为我认为它只是“删除”一段代码(如果为 false,则删除“if”部分,否则删除“else”部分)。但为什么
if consteval
不做同样的事情呢? 还有其他方法可以做到这一点吗?
consteval
if 语句(除了对
consteval
函数调用的影响之外)本质上等同于:
if (std::is_constant_evaluated()) // if consteval
if (!std::is_constant_evaluated())) // if !consteval
constexpr
if 语句可以影响返回类型推导的原因是它们将 false 分支变成了discarded statements,使之就好像您根本没有编写该代码一样。 A
consteval
if 语句根本不会执行两个分支之一,就像常规 if 语句一样。