基于模板的 switch 语句的 if constexpr
if constexpr for a switch statement based on a template
我有一个与此类似的模板,它定义了一些模板的特定代码:
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;
}
}
}
}
PS。我知道我可以将此开关一分为二,但我不想这样做,因为它会阻碍编译器优化。
阅读 [stmt.if] 告诉我们您的代码是 ill-formed。 if constexpr
中的 case 标签只能引用完全包含在 if 语句中的开关。
A case or default label appearing within such an if statement shall be
associated with a switch statement within the same if statement. A
label declared in a substatement of a constexpr if statement shall
only be referred to by a statement in the same substatement.
您不能从外部跳转到废弃的语句。但如果有任何安慰,您可以标记 if constexpr
本身。
我手边没有权威消息来源,但我担心这不可能。
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.
我有一个与此类似的模板,它定义了一些模板的特定代码:
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;
}
}
}
}
PS。我知道我可以将此开关一分为二,但我不想这样做,因为它会阻碍编译器优化。
阅读 [stmt.if] 告诉我们您的代码是 ill-formed。 if constexpr
中的 case 标签只能引用完全包含在 if 语句中的开关。
A case or default label appearing within such an if statement shall be associated with a switch statement within the same if statement. A label declared in a substatement of a constexpr if statement shall only be referred to by a statement in the same substatement.
您不能从外部跳转到废弃的语句。但如果有任何安慰,您可以标记 if constexpr
本身。
我手边没有权威消息来源,但我担心这不可能。
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.