在以下 C++20 函数模板中:
template<int i>
void f() {
if constexpr (i == 1)
g();
else if constexpr (i == 2)
h();
else
??? // <--error
}
我们可以在???
中写些什么吗?这样调用 f<3>()
会在编译时失败吗?
最佳答案
问题是constexpr if的丢弃语句不可能对每一个可能的特化都是病态的。 [temp.res.general]/6
(强调我的)
The validity of a template may be checked prior to any instantiation.
The program is ill-formed, no diagnostic required, if:
- no valid specialization can be generated for a template or a substatement of a constexpr if statement within a template and the template is not instantiated, or
您可以使用始终为 false
的依赖于类型的表达式。例如
template<int i> struct dependent_false : std::false_type {};
template<int i>
void f() {
if constexpr (i == 1)
g();
else if constexpr (i == 2)
h();
else
static_assert(dependent_false<i>::value, "Must be 1 or 2");
}
关于c++ - 如何在 constexpr if-else 链中导致静态错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66363972/