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 然后进入内部.强类型 enums 也是如此.
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 enums.
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 enums. 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"对于范围枚举?
基础教程推荐
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
