I'm probably missing something but I'm working with a code base that uses a lot of
typedef enum foo
{
....
} foo;
Is this just the same as an enum class but not strongly typed?
I'm probably missing something but I'm working with a code base that uses a lot of
typedef enum foo
{
....
} foo;
Is this just the same as an enum class but not strongly typed?
Using typedef enum
does something different than enum class
.
The use of typedef enum
, as @UnholySheep mentioned in the comments, is mostly a C idiom that isn't needed in C++. In C, if you declared an enum
like this:
enum Ghost {
Blinky,
Pinky,
Inky,
Clyde
};
then to declare a variable of type Ghost
, you'd have to say
enum Ghost oneGhost;
The use of "enum
" here could be a bit annoying, so a pattern emerged of writing out the enum
declaration as
typedef enum Ghost {
Blinky,
Winky,
Pinky,
Clyde
} Ghost;
This says "there's a type called enum Ghost
defined as usual, but you can just call it Ghost
for short. That way, in C, you could write
Ghost myGhost;
and have everything you need.
However, C++ dropped the requirement to use enum
this way. If you have a Ghost
defined using the first (typedef
-free) version of the code, you could just say Ghost myGhost;
just fine. In that sense, there's not much reason to use typedef enum
in C++.
This is quite different than enum class
. In C++, enum class
has the advantage that the constants defined in the enumeration don't end up as part of the namespace in which the enum
was defined, and you can't implicitly convert from an enum class
to an integer type. In that sense, enum class
is mostly about type safety and making it hard to make mistakes with an enum
.
Hope this helps!