我正在使用一个范围枚举来枚举我正在实现的某个状态机中的状态.例如,让我们说:
enum class CatState
{
sleeping,
napping,
resting
};
Run Code Online (Sandbox Code Playgroud)
在我定义状态转换表的cpp文件中,我想使用等价的东西,using namespace X
这样我就不需要为我的所有州名添加前缀CatState::
.换句话说,我想用sleeping
而不是CatState::sleeping
.我的转换表有很多列,因此避免使用CatState::
前缀会使事情变得更紧凑和可读.
那么,有没有办法避免一直打字CatState::
?
是的,是的,我已经意识到了陷阱using namespace
.如果有强类型枚举的等价物,我保证只在我的cpp实现文件中的有限范围内使用它,而不是邪恶.
Nic*_*las 19
那么,有没有办法避免一直打字
CatState::
?
没有.就像没有必要ClassName::
为静态类成员键入一样.你不能说using typename ClassName
,然后得到内部.强类型enum
s也是如此.
您当然不能使用using enum X
语法,只需使用常规enum class
s.但是你失去了强烈的打字.
应该注意的是,对于弱类型枚举使用ALL_CAPS的原因之一是避免名称冲突.一旦我们有完整的作用域和强类型,枚举的名称是唯一标识的,不能与其他名称冲突.能够将这些名称带入命名空间范围将重新引入此问题.因此,您可能希望再次使用ALL_CAPS来帮助消除名称的歧义.
小智 15
因此,简短的答案是否定的,但是幸运的是,这将在最近完成的C ++ 20功能集中改变。根据接受的建议,您将可以执行以下操作:
enum class CatState
{
sleeping,
napping,
resting
};
std::string getPurr(CatState state)
{
switch (state)
{
using enum CatState;
// our states are accessible without the scope operator from now on
case sleeping: return {}; // instead of "case CatState::sleeping:"
case napping: return "purr";
case resting: return "purrrrrr";
}
}
Run Code Online (Sandbox Code Playgroud)
Jam*_*lis 10
您可以考虑使用a typedef
来缩短限定名称:
typedef CatState C;
Run Code Online (Sandbox Code Playgroud)
或者,如果列的重复方式可以轻松生成,您可以考虑使用宏来生成表中的每一行,这样可以生成非常简洁(也更容易阅读)的代码.