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

在以下 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");
}

https://stackoverflow.com/questions/66363972/

相关文章:

java - 如何使用流将映射值聚合到集合中

python - 获取包含在列表列表中的字典的值

modelica - 如何在创建实例之前在模型中重新声明包?

regex - 计算 Perl 中字符串中非空白字符的数量

javascript - 翻转所有卡片,但想一张一张地翻转

c++ - CMake 找不到生成的 Visual Studio 15 2017 实例,但可以与 V

c - 如何打印从 C 中的 scanf 输入整数开始递减的奇数?

javascript - 如何将共享一个公共(public)键的两个对象的两个值合并在一起并返回它?

java - 追加java静态变量

c - execl参数混淆