等效于“使用命名空间 X"对于范围枚举? [英] Equivalent of "using namespace X" for scoped enumerations?

查看:21
本文介绍了等效于“使用命名空间 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"对于范围枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆