Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map C++ enums as const char*

Tags:

c++

dictionary

I have the following enum and map:

typedef enum {
    MaxX = 0,
    MaxY,
    MaxCells,
    MaxCycles,
    Threes
} SettingName;

typedef std::map<SettingName, const char*> SettingNameCollection;

SettingNameCollection settingNames;

And I have the following function to return the enum name:

const char* gofBoard::getSettingName(unsigned x) {
    return settingNames[static_cast<SettingName>(x)];
}

And from what I've read that should work, but the function doesn't return anything. There's no compile time errors, and no runtime errors.

like image 512
Krzaku Avatar asked Oct 28 '25 05:10

Krzaku


1 Answers

Here's my suggestion:

1- Write this macro:

#define SMART_STRINGIFY_CASE(ENUM_CODE) case ENUM_CODE: return # ENUM_CODE

2- Write this function:

const char* SettingNamesToString( settingNames const input)
{
  switch(input)
  {
    SMART_STRINGIFY_CASE(MaxX);
    SMART_STRINGIFY_CASE(MaxY);
    ...
  default:
    // your own ! 
}
like image 181
0x26res Avatar answered Oct 29 '25 20:10

0x26res