Created
October 19, 2018 15:52
-
-
Save eplawless/3b081d5dfc9a402f7451159c068e0dcb to your computer and use it in GitHub Desktop.
Hack to get type-safe enum classes with implicit conversion to int.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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