-2

I have a header file that will eventually include more than one enum class. However, when I include the header file in another file and try to use the enum class, my program will not compile. For example:

enums.h:

#ifndef ENUMS_H
#define ENUMS_H

enum class TokenType : char
{
     IDEN,
     STRING,
     SEMICO
};

#endif

and main.cpp:

#include <iostream>
#include "enums.h"

int main()
{
     char token = TokenType::STRING; //Does not compile!
}

However, when I use a regular enum, it compiles correctly:

enums.h:

#ifndef ENUMS_H
#define ENUMS_H

enum TokenType : char
{
     IDEN,
     STRING,
     SEMICO
}

#endif

and main.cpp:

#include <iostream>
#include "enums.h"

int main()
{
     char token = STRING; //This does compile!
}

Does anyone know how to do this correctly? I've searched a lot and came up with nothing.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
  • http://coliru.stacked-crooked.com/a/31bbc9e67f0ebd36 – πάντα ῥεῖ Feb 16 '19 at 09:59
  • `TokenType` is *not* a `char` even if its underlying type is. It is its own type and does not implicitly convert. You need to use a variable of the correct (`TokenType`) type or use an explicit cast. This, by the way, is a *good* thing compared to old `enum`s. – Jesper Juhl Feb 16 '19 at 10:02

2 Answers2

3

enum class do not participate in implicit conversion whereas unscoped enums do. Thus,

int main()
{
     TokenType token = TokenType::STRING;
}

will compile.

You can see How to automatically convert strongly typed enum into int? how to otherwise convert an enum class to some other value.

Bo R
  • 2,334
  • 1
  • 9
  • 17
0

Enum is strongly type and you cannot assign enum to an int or char without casting it. You can try:

int main() 
{
  char token = (char)TokenType::STRING; 
}
Patryk kowalski
  • 313
  • 2
  • 5
  • 18
  • Prefer C++style casts over C-style casts if you *must* use a cast (always prefer *not* to). In this case `static_cast`. – Jesper Juhl Feb 16 '19 at 10:08