如何断言constexpr if else子句永远不会发生? [英] How to assert that a constexpr if else clause never happen?

查看:88
本文介绍了如何断言constexpr if else子句永远不会发生?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果条件为真,我想在非constexpr时引发编译时错误,例如:

I want to raise a compile time error when non of the constexpr if conditions is true eg:

if constexpr(condition1){
    ...
} else if constexpr (condition2) {
   ....
} else if constexpr (condition3) {
  ....
} else {
    // I want the else clause never taken. But I heard the code below is not allowed
    static_assert(false);
}

// I'd rather not repeat the conditions again like this:
static_assert(condition1 || condition2 || condition3);


推荐答案

您必须使废弃的语句依赖于模板参数

You have to make the discarded statement dependent of the template parameters

template <class...> constexpr std::false_type always_false{};

if constexpr(condition1){
    ...
} else if constexpr (condition2) {
   ....
} else if constexpr (condition3) {
  ....
} else {       
    static_assert(always_false<T>);
}

之所以这样,是因为


[temp.res] / 8 -该程序格式错误,无需诊断,如果

[temp.res]/8 - The program is ill-formed, no diagnostic required, if

无法为模板的模板或子语句生成有效的专业化名称 constexpr 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 ...

这篇关于如何断言constexpr if else子句永远不会发生?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆