Skip to content

Instantly share code, notes, and snippets.

@marcinwol
Created March 1, 2015 02:27
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 marcinwol/f1aca466262927cfa39c to your computer and use it in GitHub Desktop.
Save marcinwol/f1aca466262927cfa39c to your computer and use it in GitHub Desktop.
C++11: enum to string and integer
/* 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