Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 488
paulm Avatar asked Jan 11 '15 23:01

paulm


People also ask

Can enum be used in switch case in C?

We can use enums in C for multiple purposes; some of the uses of enums are: To store constant values (e.g., weekdays, months, directions, colors in a rainbow) For using flags in C. While using switch-case statements in C.

Are enums evaluated at compile time?

Enums allow us to define or declare a collection of related values that can be numbers or strings as a set of named constants. Unlike some of the types available in TypeScript, enums are preprocessed and are not tested at compile time or runtime.

Are enums compile time?

Enum values or Enum instances are public, static, and final in Java. They are a compile-time constant, which means you can not changes values of Enum instances and further assignment will result in a compile-time error. 9.

Can enum class be used in switch case in C++?

An enumeration type is still an enumeration type even whether strongly typed or not, and have always worked fine in switch statements.


2 Answers

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.

like image 153
user14717 Avatar answered Sep 28 '22 10:09

user14717


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;
  }
}
like image 44
James Akwuh Avatar answered Sep 28 '22 10:09

James Akwuh