Click here to Skip to main content
15,886,017 members
Articles / Programming Languages / C++
Tip/Trick

Enum to String, Take 2

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
16 Mar 2019MIT 3.8K   1
How to convert enum to string

Thanks to Sebastian Mestre (who commented on my previous post), I learned something new today. 🙂 The X macro makes the enum to string code much… well, perhaps not cleaner, but shorter. 😉 It also solves the problem of having to update the code in 2 places: first in the enum itself, second in the enum to string map.
Without further ado, I present to you the X macro:

And the complete implementation goes something like this:

C++
#include <iostream>

#define MY_ENUM \
    X(V1) \
    X(V2) \
    X(V3)

#define X(name) name,

enum MyEnum
{
    MY_ENUM
};

#undef X

constexpr const char* MyEnumToString(MyEnum e) noexcept
{
    #define X(name) case(name): return #name;
    switch(e)
    {
        MY_ENUM
    }
    #undef X
}

int main(int argc, char** argv)
{
    std::cout << MyEnumToString(V1) << std::endl;
    std::cout << MyEnumToString(V2) << std::endl;
    std::cout << MyEnumToString(V3) << std::endl;
    return 1;
}

In this version, we only have to update the MY_ENUM macro. The rest is taken care of by the preprocessor.

Update

Here’s the same approach that works with strongly typed enums:

C++
#include <iostream>

#define MY_ENUM \
X(V1) \
X(V2) \
X(V3)

#define X(name) name,

#define MY_ENUM_NAME MyEnum

enum class MY_ENUM_NAME : char
{
    MY_ENUM
};

#undef X

constexpr const char* MyEnumToString(MyEnum e) noexcept
{
#define X(name) case(MY_ENUM_NAME::name): return #name;
    switch(e)
    {
            MY_ENUM
    }
#undef X
}

int main(int argc, char** argv)
{
    std::cout << MyEnumToString(MyEnum::V1) << std::endl;
    std::cout << MyEnumToString(MyEnum::V2) << std::endl;
    std::cout << MyEnumToString(MyEnum::V3) << std::endl;
    return 1;
}
This article was originally posted at https://vorbrodt.blog/2019/01/29/enum-to-string-take-2

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Software Developer (Senior)
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionAnother options Pin
Dean Roddey17-Mar-19 7:06
Dean Roddey17-Mar-19 7:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.