mardi 3 mars 2015

enum to string in modern C++ (C++14) and future C++17

Yet another recurrent duplicated question:



But after reading many answers, I did not yet find any:



  • Elegant way using C++11/C++14 new features

  • Or something ready-to-use in Boost

  • Else something planned for C++17


Please do not provide C macro-based answers if possible.

EDIT: As pointed out by Vittorio Romeo and PlasmaHH, we have to use macro-based solutions for many years (C++17 release + compilers implementation + projects adoption). Therefore unprecedented awesome macro-based answers can be provided. But please be exhaustive, realize a state of the art and provide tested C++14-friendly snippets (avoid invaluable duplication of other answers and basic link).


For instance a replacement of the below code (without maintenance of enum/string mapping).

You can compile and execute it on Coliru.



#include <cstdint> // for std::uint_fast8_t
#include <array>
#include <string>
#include <iostream>

enum class MyEnum : std::uint_fast8_t {
AAA,
BBB,
CCC,
};

std::array<std::string,3> MyEnumStrings {
"AAA",
"BBB",
"CCC"
};

int main()
{
std::cout << MyEnumStrings[ static_cast<std::size_t>(MyEnum::AAA) ] <<'\n';
}

Aucun commentaire:

Enregistrer un commentaire