Click here to Skip to main content
13,900,571 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

1.1K views
Posted 16 Mar 2019
Licenced MIT

Enum to String, Take 2

, 16 Mar 2019
Rate this:
Please Sign up or sign in to vote.
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:

#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:

#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;
}

License

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

Share

About the Author

Martin Vorbrodt
Software Developer (Senior)
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

 
QuestionAnother options Pin
Dean Roddey17-Mar-19 7:06
memberDean 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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web02 | 2.8.190306.1 | Last Updated 16 Mar 2019
Article Copyright 2019 by Martin Vorbrodt
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid