c++ - 基于模板的 switch 语句的 if constexpr

标签 c++ visual-studio-2017 c++17

我有一个与此类似的模板,它定义了一些模板的特定代码:

template <typename T>
class CMyClass : public T
{

template<typename T>
inline void CMyClass<T>::SomeFunc()
{
    if constexpr(std::is_same_v<T, CSpecialClass>)
    {
        DoSpecialClassActions();
        //...
    }
    else
    {
        DoGenericActions();
        //...
    }
}


}

但现在我很好奇是否可以在 switch 语句中使用类似的 constexpr 条件? (根据模板添加额外的 case 语句。)

像这样的东西(不编译):

template<typename T>
inline void CMyClass<T>::SomeSwitchFunc()
{
    switch(message)
    {
        case 1:
            doMsg1();
            //...
            break;
        case 2:
            doMsg2();
            //...
            break;
        //...

        if constexpr(std::is_same_v<T, CSpecialClass>)
        {
        case 10:
            doMsg10();
            //...
            break;
        }
    }
}

}

附言。我知道我可以将此开关分成两部分,但我不想这样做,因为它会阻碍编译器优化。

最佳答案

我手头没有权威来源,但我担心这是不可能的。

cppreference page on if-statements状态:

Labels (goto targets, case labels, and default:) appearing in a substatement of a constexpr if can only be referenced (by switch or goto) in the same substatement.

关于c++ - 基于模板的 switch 语句的 if constexpr,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56747118/

相关文章:

c++ - 64 位 C++ 二进制文件消耗大量内存,即使二进制文件很大

c++ - 使用 IsWow64Process 而不是单独编译

c++ - MPI,更大的阵列

visual-studio - 如何在Visual Studio 2017中更改调试端口?

c# - VS 2017 .Net core 2.2 中缺少 Blazor 模板

c# - 在 C++ 中使用 Mono 获取程序集类

c++ - 超出范围时如何重置多个变量?

java - 更改Java中对象的地址(再次按值传递??)

c++ - 是否有构造函数/析构函数方法的总称?

c++ - 修改不可变子结构