Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if constexpr for a switch statement based on a template

I have a template constructed similar to this, that defines code specific for some templates:

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();
        //...
    }
}


}

But now I'm curious if I can use similar constexpr condition in a switch statement? (To add additional case statements based on the template.)

Something like this (which does not compile):

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;
        }
    }
}

}

PS. I know that I can separate this switch into two, but I don't want to do it, as it will thwart compiler optimization.

like image 531
c00000fd Avatar asked Apr 28 '26 13:04

c00000fd


1 Answers

I don't have an authoritative source at hand, but I fear this is not possible.

the cppreference page on if-statements states:

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.

like image 174
Hulk Avatar answered May 01 '26 02:05

Hulk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!