Created
March 1, 2015 02:27
-
-
Save marcinwol/f1aca466262927cfa39c to your computer and use it in GitHub Desktop.
C++11: enum to string and integer
This file contains 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
/* How to use enum class and to obtain its value as integer and string | |
* without too much of code repition. | |
* | |
* Based on http://stackoverflow.com/a/238157/248823 | |
*/ | |
#include <iostream> | |
using namespace std; | |
#define SOME_ENUM(DO) \ | |
DO(JPEG) \ | |
DO(DCM) \ | |
DO(PNG) | |
#define MAKE_ENUM(VAR) VAR, | |
enum class IMAGE_TYPES | |
{ | |
SOME_ENUM(MAKE_ENUM) | |
}; | |
#define MAKE_STRINGS(VAR) #VAR, | |
const char* const | |
IMAGE_TYPES_NAMES[] = | |
{ | |
SOME_ENUM(MAKE_STRINGS) | |
}; | |
const char * | |
GET_IMAGE_NAME(IMAGE_TYPES type) | |
{ | |
return IMAGE_TYPES_NAMES[static_cast<int>(type)]; | |
} | |
int | |
GET_IMAGE_VALUE(IMAGE_TYPES type) | |
{ | |
return static_cast<int>(type); | |
} | |
int main() | |
{ | |
IMAGE_TYPES type; | |
type = IMAGE_TYPES::PNG; | |
int type_value {GET_IMAGE_VALUE(type)}; | |
string type_name {GET_IMAGE_NAME (type)}; | |
cout << type_value << ": " << type_name << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment