简体   繁体   中英

How to cast int to enum in C++?

How do I cast an int to an enum in C++?

For example:

enum Test
{
    A, B
};

int a = 1;

How do I convert a to type 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:

5.2.9 Static cast

... 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); is well-formed, for some invented temporary variable 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:

auto result = Test(a);

Test castEnum = static_cast<Test>(a-1); will cast a to A . If you don't want to substruct 1, you can redefine the enum :

enum Test
{
    A:1, B
};

In this case Test castEnum = static_cast<Test>(a); could be used to cast a to 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 Test : int {A, B};
int a = 1;
Test val{a};

and, of course, Test val{1}; is also valid.

The relevant cppreference part reads (emphasis mine):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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