Enum to string in C++11

后端 未结 6 1813
囚心锁ツ
囚心锁ツ 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:25

    In my opinion, the most maintainable approach is to write a helper function:

    const char* get_name(OS_type os) {
      switch (os) {
      case Linux: return "Linux";
      case Apple: return "Apple";
      case Windows: return "Windows";
      }
    }
    

    It is a good idea not to implement the "default" case, since doing so will ensure that you get a compiler warning if you forget to implement a case (with the right compiler and compiler settings).

提交回复
热议问题