paulm
paulm

Reputation: 5882

C++11 mixing enum class and unsigned int in switch case will not compile

Why doesn't this code compile, and what can I do to make it compile?

#include <iostream>
using namespace std;

enum class myEnum : unsigned int
{
    bar = 3
};

int main() {
    // your code goes here

    unsigned int v  = 2;
    switch(v)
    {
        case 2:
        break;

        case myEnum::bar:
        break;
    }

    return 0;
}

ideone:

https://ideone.com/jTnVGq

prog.cpp: In function 'int main()':
prog.cpp:18:16: error: could not convert 'bar' from 'myEnum' to 'unsigned int'
   case myEnum::bar:

Fails to build in GCC and Clang, works in MSVC 2013.

Upvotes: 8

Views: 10032

Answers (4)

Mike Mutabazi
Mike Mutabazi

Reputation: 1

An example of enum using classes and switch case , this is the proper way to call an enum class from another class.

class MyClass 
{
public:

enum class colors {yellow , blue , green} ; 

};


int main ()
{

Myclass::colors c = Myclass::colors::yellow;
 
switch(c)
{
case Myclass::colors::yellow:
cout <<"This is color yellow \n"
case Myclass::colors::blue:
cout <<"This is color blue\n"

}

return 0 ; 
} 

Upvotes: -1

James Akwuh
James Akwuh

Reputation: 2217

You can simply use such a syntax:

enum class Test { foo = 1, bar = 2 };
int main()
{
  int k = 1;
  switch (static_cast<Test>(k)) {
    case Test::foo: /*action here*/ break;
  }
}

Upvotes: 5

Phil Wright
Phil Wright

Reputation: 180

An alternative that keeps using enum class is to add a new field that represents a value of 2 to myEnum. Then you can change unsigned int v to myEnum v.

enum class myEnum : unsigned int
{
    foo = 2,
    bar = 3
};

int main() {
    myEnum v = myEnum::foo;
    switch(v)
    {
        case myEnum::foo:
        break;

        case myEnum::bar:
        break;
    }
}

Upvotes: 2

user14717
user14717

Reputation: 5151

The whole purpose of the enum class was so that its members couldn't be compared directly to ints, ostensibly improving the type safety of C++11 relative to C++03. Remove class from enum class and this will compile.

To quote Lord Bjarne:

(An) enum class (a scoped enumeration) is an enum where the enumerators are within scope of the enumeration and no implicit conversions to other types are provided.

Upvotes: 12

Related Questions