enum to string in modern C++11 / C++14 / C++17 and future C++20

后端 未结 28 2242
逝去的感伤
逝去的感伤 2020-11-22 16:57

Contrary to all other similar questions, this question is about using the new C++ features.

  • 2008 c Is there a simple way to convert C++ enum to string?
  • <
28条回答
  •  情话喂你
    2020-11-22 17:18

    Well, yet another option. A typical use case is where you need constants for the HTTP verbs as well as using its string version values.

    The example:

    int main () {
    
      VERB a = VERB::GET;
      VERB b = VERB::GET;
      VERB c = VERB::POST;
      VERB d = VERB::PUT;
      VERB e = VERB::DELETE;
    
    
      std::cout << a.toString() << std::endl;
    
      std::cout << a << std::endl;
    
      if ( a == VERB::GET ) {
        std::cout << "yes" << std::endl;
      }
    
      if ( a == b ) {
        std::cout << "yes" << std::endl;
      }
    
      if ( a != c ) {
        std::cout << "no" << std::endl;
      }
    
    }
    

    The VERB class:

    // -----------------------------------------------------------
    // -----------------------------------------------------------
    class VERB {
    
    private:
    
      // private constants
      enum Verb {GET_=0, POST_, PUT_, DELETE_};
    
      // private string values
      static const std::string theStrings[];
    
      // private value
      const Verb value;
      const std::string text;
    
      // private constructor
      VERB (Verb v) :
      value(v), text (theStrings[v])
      {
        // std::cout << " constructor \n";
      }
    
    public:
    
      operator const char * ()  const { return text.c_str(); }
    
      operator const std::string ()  const { return text; }
    
      const std::string toString () const { return text; }
    
      bool operator == (const VERB & other) const { return (*this).value == other.value; }
    
      bool operator != (const VERB & other) const { return ! ( (*this) == other); }
    
      // ---
    
      static const VERB GET;
      static const VERB POST;
      static const VERB PUT;
      static const VERB DELETE;
    
    };
    
    const std::string VERB::theStrings[] = {"GET", "POST", "PUT", "DELETE"};
    
    const VERB VERB::GET = VERB ( VERB::Verb::GET_ );
    const VERB VERB::POST = VERB ( VERB::Verb::POST_ );
    const VERB VERB::PUT = VERB ( VERB::Verb::PUT_ );
    const VERB VERB::DELETE = VERB ( VERB::Verb::DELETE_ );
    // end of file
    

提交回复
热议问题