简体   繁体   English

如何在 C++ 中将 typedef 枚举转换为使用枚举

[英]How to convert a typedef enum into using enum in C++

I'm trying to explore "using" in C++, and currently I would like to convert typedef into using.我正在尝试探索 C++ 中的“使用”,目前我想将 typedef 转换为使用。

For example,例如,

typedef enum tag_EnumType : int {
    A,
    B,
    C,
} EnumType;

And I tried to convert it as following我试图将其转换如下

using EnumType = enum tag_EnumType : int {
    A,
    B,
    C,
};

However, the compilation failed.但是,编译失败。 Could anyone help?有人可以帮忙吗? Thanks in advance.提前致谢。

The truth is, I'm working on a giant project.事实是,我正在做一个巨大的项目。 Some of typedef enum could be rewritten as using, but others couldn't.一些 typedef 枚举可以重写为 using,但其他则不能。 Does anyone know the reason?有谁知道原因? Is it related with namespace or sth?它与命名空间或某事有关吗?

typedef enum is a C way of creating enums. typedef enum是一种创建枚举的 C 方式。 If you want it the C++ way, you better write:如果你想要 C++ 方式,你最好写:

 enum EnumType : int {
    A,
    B,
    C,
};

In C++11 and above scoped enums are also available, that way you prevent name collisions.在 C++11 及以上范围的枚举中也可用,这样可以防止名称冲突。

 enum class EnumType : int {
    A,
    B,
    C,
};

Using statements are for other typedefs, some examples: using 语句适用于其他类型定义,一些示例:

using IntVector = std::vector<int>;
using Iterator = IntVector::Iterator;
using FuncPtr = int(*)(char, double);

As with the typedef struct construction common in C, it is simply not needed in C++.与 C 中常见的typedef struct构造一样,在 C++ 中根本不需要它。 Tag names and typedef names are not in separate namespaces.标记名称和 typedef 名称不在单独的命名空间中。

All you need is所有你需要的是

enum EnumType : int {
    A,
    B,
    C,
};

and the name EnumType will refer to the enum without need of prefixing enum , except if you want to disambiguate from non-type names.并且名称EnumType将引用枚举而不需要前缀enum ,除非您想消除非类型名称的歧义。


using is normally used only to alias a type, not declare a new one, eg: using通常仅用于对类型进行别名,而不是声明新类型,例如:

using EnumTypeAlias = EnumType;

Technically it is allowed to alias an unnamed struct or enum , but I see no reason for doing that:从技术上讲,允许为未命名的structenum起别名,但我认为没有理由这样做:

using EnumTypeAlias = enum { A, B, C };

I would also generally advice to use scoped enums , which behave differently in some ways from C-style enums, see this question .我通常还建议使用作用域枚举,它在某些方面与 C 风格的枚举不同,请参阅这个问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM