Equivalent of quot;using namespace Xquot; for scoped enumerations?(等效于“使用命名空间 X对于范围枚举?)
问题描述
我正在使用作用域枚举来枚举我正在实现的某些状态机中的状态.例如,让我们说:
I am using a scoped enum to enumerate states in some state machine that I'm implementing. For example, let's say something like:
enum class CatState
{
sleeping,
napping,
resting
};
在我定义状态转换表的 cpp 文件中,我想使用与 using namespace X
等效的东西,这样我就不需要在所有状态名称前加上 猫状态::
.换句话说,我想使用 sleeping
而不是 CatState::sleeping
.我的转换表有很多列,因此避免使用 CatState::
前缀会使内容更紧凑和可读.
In my cpp file where I define a state transition table, I would like to use something equivalent to using namespace X
so that I don't need to prefix all my state names with CatState::
. In other words, I'd like to use sleeping
instead of CatState::sleeping
. My transition table has quite a few columns, so avoiding the CatState::
prefix would keep things more compact and readable.
那么,有没有办法避免一直输入CatState::
?
So, is there a way to avoid having to type CatState::
all the time?
是的,是的,我已经意识到使用命名空间
的陷阱.如果强类型枚举有等价物,我保证只在我的 cpp 实现文件中的有限范围内使用它,而不是用于邪恶.
Yeah, yeah, I'm already aware of the pitfalls of using namespace
. If there's an equivalent for strongly-typed enums, I promise to only use it inside a limited scope in my cpp implementation file, and not for evil.
推荐答案
那么,有没有办法避免一直输入
CatState::
?
不是在 C++20 之前.就像必须为静态类成员键入 ClassName::
没有等价物一样.你不能说 using typename ClassName
然后进入内部.强类型 enum
s 也是如此.
Not before C++20. Just as there's no equivalent for having to type ClassName::
for static class members. You can't say using typename ClassName
and then get at the internals. The same goes for strongly typed enum
s.
C++20 添加了 using enum X
语法,就像它看起来的那样.
C++20 adds the using enum X
syntax, which does what it looks like.
您当然可以不使用enum class
语法,只需使用常规的enum
即可.但随后你就失去了强类型.
You can of course not use enum class
syntax, just using regular enum
s. But then you lose strong typing.
应该注意,对弱类型枚举使用 ALL_CAPS 的原因之一是为了避免名称冲突.一旦我们有了完整的作用域和强类型,枚举的名称就会被唯一标识并且不能与其他名称冲突.能够将这些名称带入命名空间范围会重新引入这个问题.因此,您可能希望再次使用 ALL_CAPS 来帮助消除名称的歧义.
It should be noted that one of the reasons for using ALL_CAPS for weakly typed enums was to avoid name conflicts. Once we have full scoping and strong typing, the name of an enum is uniquely identified and cannot conflict with other names. Being able to bring those names into namespace scope would reintroduce this problem. So you would likely want to use ALL_CAPS again to help disambiguate the names.
这篇关于等效于“使用命名空间 X"对于范围枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:等效于“使用命名空间 X"对于范围枚举?


基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01