c++ - 如何在 constexpr if-else 链中导致静态错误?

标签 c++ constexpr c++20 static-assert if-constexpr

在以下 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/

相关文章:

c++ - 为什么模板只能在头文件中实现?

c# - 使用 P/Invoke 编码 VARIANT 数组

c++ - 使用 constexpr 方法在结构内部进行模板参数化

需要以 OutputIterator 作为参数的成员函数的 C++ 概念

c++ - round()函数产生一个奇数

c++ - 将 boost 多精度与三角函数结合使用

c++ - constexpr 数组作为模板非类型参数的 MSVC 错误

c++ - 你能使用 constexpr 变量的地址吗?

c++ - 为什么协程的返回类型必须是可移动构造的?

c++ - 在裸机 Controller 上的不同上下文中设置 int 变量中的标志