Although many simple ways to do an enum-to-string or string-to-enum conversion exist, I woud like consider, here, a more generalized way.
Why doesn't C++ allow native contruct for it? There are mainly two reasons:
The first is technical: C++ doesn't have any reflection mechanism: compiled symbols simple cease to exist (and become just numbers). And since they don't exist, you cannot get them back.
The second is more a programming issue: enumerals are "shared" between the compiler and the programmer. String literals are shared between the progam and the end-user. That may be not a programmer and may not speak English (and we don't know what he speaks).
A general way to solve the problem is so to spkit it in two parts: one is at stream level, and the other at localization level.
What does it happen when you write std::cout << 42
?
The operator<<(ostream&, int)
implementation, in fact calls use_facet<num_put<char> >(cout.getloc()).do_put(int)
which in turn use eventually the numpunct
facet that define how to handle signs, decimal separator and digit group separators.
The standard way to handle enumeral output is so, by implementing an ostrea<<enumeral
operator that gets a facet and calls on it a method to actually write that string.
Such a facet can them be implemented a number of times and made available for each supported language.
That's not easy and straightforward, but that's how C++ I/O is conceived.
Once you did all that, the idiomatic way to get a string is using a strngstream imbued with a local that supports all the enums and classes required facets.
Too complex? may be. But if you think this is too complicated, stop to teach std::cout << "Hello wrld" << std::endl;
and write a more simple "output library".