Alex F
Alex F

Reputation: 43311

Cannot convert enum class to int using static_cast

enum class TestEnum : int
{
    first,
    second
};

int main()
{
    int n = static_cast<int>(TestEnum::second);   // error
    return 0;
}

Build log:

g++ -O0 -g3 -Wall -c -fmessage-length=0 -std=c++0x -MMD -MP -MF"src/test.d" -MT"src/test.d" -o "src/test.o" "../src/test.cpp"
../src/test.cpp: In function ‘int main()’:
../src/test.cpp:20:20: error: cannot convert ‘TestEnum’ to ‘int’ in initialization

gcc version 4.6.3

How can I convert enum class instance to int?

Upvotes: 3

Views: 8425

Answers (2)

Sushil88
Sushil88

Reputation: 7

Upgrade your compiler to 4.7 and use -std=c++11 or -std=gnu++11 instead -std=c++0x. scoped enums only available with -std=c++11 or -std=gnu++11

Upvotes: 0

yakov
yakov

Reputation: 454

You are trying to compile you code with -std=c++0x key. But the strong type enumeration enum class is a C++11 feature, so you'd better use the newer GCC compiler. GCC 4.7 or better is suitable, it has the -std=c++11 command line key: http://gcc.gnu.org/projects/cxx0x.html

This code works: http://ideone.com/4IQPUx

Upvotes: 2

Related Questions