Skip to content

Instantly share code, notes, and snippets.

@eplawless
Created October 19, 2018 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eplawless/3b081d5dfc9a402f7451159c068e0dcb to your computer and use it in GitHub Desktop.
Save eplawless/3b081d5dfc9a402f7451159c068e0dcb to your computer and use it in GitHub Desktop.
Hack to get type-safe enum classes with implicit conversion to int.
#include <iostream>
#define ENUM_CLASS(Name, ...) \
struct Name { \
static int sCounter; \
int mValue; \
Name() : mValue(++Name::sCounter) {} \
operator int() { return mValue; } \
static Name __VA_ARGS__; \
}; \
int Name::sCounter = 0; \
ENUM_CLASS(Color, Red, Green);
Color Color::Red; // should be unnecessary with some macro crimes
Color Color::Green;
int main(int argc, char **argv)
{
Color c = Color::Red;
// c = 10; <-- compile error
std::cout << c << std::endl; // prints 1
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment