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.
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.