在以下代码示例中,if
声明取决于 bool
模板参数,它是一个编译时常量。编译器以不同的方式处理此代码:
else
中的模板函数分支缺乏对 true
的特化模板参数值(即使它从未被调用过)。 if
在编译时声明并在链接之前删除未使用的分支。 问题是哪种行为符合标准(或者它是未定义的行为并且两者都以自己的方式正确)?
#include <iostream>
template<const bool condition>
struct Struct
{
void print()
{
if (condition)
{
std::cout << "True\n";
}
else
{
printIfFalse();
}
}
private:
void printIfFalse();
};
template <>
void Struct<false>::printIfFalse()
{
std::cout << "False\n";
}
int main()
{
Struct<true> withTrue{};
withTrue.print();
Struct<false> withFalse{};
withFalse.print();
return 0;
}
最佳答案
所有编译器的行为都正确。
您的程序格式错误,不需要诊断,因为您使用的是 odr Struct<true>::printIfFalse
通过 Struct<true>::print()
的实例化需要来自 withTrue.print();
中的调用.在丢弃语句之外使用 odr 的函数必须在程序中有定义,参见 [basic.def.odr]/4 ,否则程序格式错误,无需诊断。
如果你使用 if constexpr
,你会得到一个废弃的语句。在模板中,并且语句不在所选分支中。因此,您可以使用 if constexpr
来使程序格式良好。而不是 if
.这是一个 C++17 特性。
关于c++ - C++ 中 if/else 分支的编译时消除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60885314/