Can C++ ever have a standard library facility(like a manipulator etc.) to output enumerators as strings corresponding to their names rather than as ints ?
Asked
Active
Viewed 792 times
0
-
I doubt it. BTW, such broad questions are off topic at SO. – R Sahu Jul 15 '17 at 05:35
-
1No it can't. The enumerated names are mapped to corresponding integral values by the compiler, and no longer exist (e.g. as a set of strings associated with the enumerated type) at run time. A library facility like a manipulator therefore has no means to access the original name, given a value. If you want to obtain a string from values of an enumerated type, you need to implement the mapping in code. – Peter Jul 15 '17 at 05:39
-
Enumeration values are actually [_named constants_](https://stackoverflow.com/questions/40018653/in-a-type-trait-why-do-people-use-enum-rather-than-static-const-for-the-value/40020448#40020448). Can you output as string the name of any other named constant? No, you can't. So it isn't a missed feature of enumerations, it's something the language prohibits in general. – skypjack Jul 15 '17 at 06:05
-
@Peter: "*A library facility like a manipulator therefore has no means to access the original name, given a value.*" A *regular* library facility? No. But the *standard* library doesn't have to follow C++'s rules. There are many standard library features that *cannot* be implemented by a user. Many of the type traits, etc. The OP would be talking about something like that. – Nicol Bolas Jul 15 '17 at 14:05
1 Answers
0
The short answer is no. For native support you need reflection like in Java or C#. Reflection for C++ is still not in standard but can be introduced in coming standards. By now I can recommend following approach:
enum class MyEnum
{ One, Two };
std::map<MyEnum, std::string> MeEnumAsString = { {MyEnum::One, "One"}, {MeEnum::Two, "Two"} };
std::cout << MyEnumAsString.at(MyEnum::One);

Viktor
- 1,004
- 1
- 10
- 16