Enum to string in C++11

后端 未结 6 1815
囚心锁ツ
囚心锁ツ 2021-02-03 21:52

I realize this has been asked before more than once on SO but I couldn\'t find a question explicitly looking for a current solution to this issue with C++11, so here we go again

6条回答
  •  野性不改
    2021-02-03 22:18

    The longstanding and unnecessary lack of a generic enum-to-string feature in C++ (and C) is a painful one. C++11 didn't address this, and as far as I know neither will C++14.

    Personally I'd solve this problem using code generation. The C preprocessor is one way--you can see some other answers linked in the comments here for that. But really I prefer to just write my own code generation specifically for enums. It can then easily generate to_string (char*), from_string, ostream operator<<, istream operator<<, is_valid, and more methods as needed. This approach can be very flexible and powerful, yet it enforces absolute consistency across many enums in a project, and it incurs no runtime cost.

    Do it using Python's excellent "mako" package, or in Lua if you're into lightweight, or the CPP if you're against dependencies, or CMake's own facilities for generating code. Lots of ways, but it all comes down to the same thing: you need to generate the code yourself--C++ won't do this for you (unfortunately).

提交回复
热议问题