Yet another recurrent duplicated question:
- 2008 c Easy way to use variables of enum types as string in C?
- 2008 c++ How to easily map c++ enums to strings
- 2008 c++ Making something both a C identifier and a string?
- 2008 c++ Is there a simple script to convert C++ enum to string?
- 2009 c++ How to use enums as flags in C++?
- 2011 c++ How to convert an enum type variable to a string?
- 2011 c++ Enum to String C++
- 2011 c++ How to convert an enum type variable to a string?
- 2012 c How to convert enum names to string in c
- 2013 c Stringifying an conditionally compiled enum in C
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