Monday, June 29, 2015

C++ Enum to String

Here is the simpliest (I think) boost-preprocessor library based approach (from stackoverflow) for converting enum values to string:

#include <boost/preprocessor.hpp>

#define X_ENUM_STRING_TOSTRING_CASE(r, data, elem)                          \
    case elem : return BOOST_PP_STRINGIZE(elem);

#define ENUM_STRING(name, enumerators)                                      \
enum name                                                                   \
{                                                                           \
    BOOST_PP_SEQ_ENUM(enumerators)                                          \
};                                                                          \
                                                                            \
inline const char* toString(name val)                                       \
{                                                                           \
    switch (val)                                                            \
    {                                                                       \
        BOOST_PP_SEQ_FOR_EACH(                                              \
            X_ENUM_STRING_TOSTRING_CASE,                                    \
            name,                                                           \
            enumerators                                                     \
        )                                                                   \
        default:                                                            \
            assert(false); return "[Unknown " BOOST_PP_STRINGIZE(name) "]"; \
    }                                                                       \
}

// Usage sample:

ENUM_STRING(Button, (Ok)(Close)(Retry)(Yes)(No)(Abort)(Help)(Cancel))

void foo()
{
    std::string btnHelpName  = toString(Button::Help);  // btnHelpName  == "Help"
    std::string btnCloseName = toString(Button::Close); // btnCloseName == "Close"
}

No comments:

Post a Comment