我有一个与此类似的模板,它定义了一些模板的特定代码:
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/