简体   繁体   English

如何在 C++ 中将 int 转换为枚举?

[英]How to cast int to enum in C++?

How do I cast an int to an enum in C++?如何将 int 转换为 C++ 中的枚举?

For example:例如:

enum Test
{
    A, B
};

int a = 1;

How do I convert a to type Test::A ?如何将a转换为类型Test::A

int i = 1;
Test val = static_cast<Test>(i);
Test e = static_cast<Test>(1);

Your code你的代码

enum Test
{
    A, B
}

int a = 1;

Solution解决方案

Test castEnum = static_cast<Test>(a);

Spinning off the closing question, "how do I convert a to type Test::A " rather than being rigid about the requirement to have a cast in there, and answering several years late only because this seems to be a popular question and nobody else has mentioned the alternative, per the C++11 standard:分拆结束的问题,“我如何将 a 转换为类型Test::A ”,而不是严格要求在那里有一个演员,并且迟到几年才回答,因为这似乎是一个受欢迎的问题,没有其他人根据 C++11 标准提到了替代方案:

5.2.9 Static cast 5.2.9 静态转换

... an expression e can be explicitly converted to a type T using a static_cast of the form static_cast<T>(e) if the declaration T t(e); ... 如果声明T t(e);则表达式e可以使用static_cast static_cast<T>(e)形式的 static_cast 显式转换为类型T is well-formed, for some invented temporary variable t (8.5).对于一些发明的临时变量t (8.5) 是良构的。 The effect of such an explicit conversion is the same as performing the declaration and initialization and then using the temporary variable as the result of the conversion.这种显式转换的效果与执行声明和初始化,然后使用临时变量作为转换的结果相同。

Therefore directly using the form t(e) will also work, and you might prefer it for neatness:因此,直接使用t(e)形式也可以,您可能更喜欢它的简洁性:

auto result = Test(a);

Test castEnum = static_cast<Test>(a-1); will cast a to A .a投射到A If you don't want to substruct 1, you can redefine the enum :如果您不想子结构 1,您可以重新定义enum

enum Test
{
    A:1, B
};

In this case Test castEnum = static_cast<Test>(a);在这种情况下Test castEnum = static_cast<Test>(a); could be used to cast a to A .可用于将a强制转换为A

Just to mention it, if the underlying type of the enum happens to be fixed, from C++17 on, it is possible to simply write顺便提一下,如果enum的底层类型恰好是固定的,从 C++17 开始,可以简单地写

enum Test : int {A, B};
int a = 1;
Test val{a};

and, of course, Test val{1};当然还有Test val{1}; is also valid.也是有效的。

The relevant cppreference part reads (emphasis mine):相关的cppreference部分内容如下(强调我的):

An enumeration can be initialized from an integer without a cast, using list initialization, if all of the following are true:如果满足以下所有条件,则可以使用列表初始化从不进行强制转换的整数初始化枚举:

  • the initialization is direct-list-initialization初始化是直接列表初始化
  • the initializer list has only a single element初始化列表只有一个元素
  • the enumeration is either scoped or unscoped with underlying type fixed枚举是作用域的或非作用域的,基础类型是固定的
  • the conversion is non-narrowing转换是非缩小的

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

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