Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert enum class to int using static_cast

Tags:

c++

enums

gcc

c++11

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?

like image 964
Alex F Avatar asked May 19 '26 19:05

Alex F


1 Answers

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

like image 68
yakov Avatar answered May 21 '26 11:05

yakov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!