Converting enum values to strings in C++ Question 1: functionxxx_as_string() is used below.  How else could it be more elegantly named?

Question 2: Is the static char* array method adopted below the only solution?  Best solution?  Any suggestions?

Generally, I have this issue where my list of enums will be from 3 - say 50 items, mostly less than 20 items and they are fairly static.

   #include &lt;iostream&gt;

   enum thing_type
   {
      DTypeAnimal,
      DTypeMineral,
      DTypeVegetable,
      DTypeUnknown
   };

   class thing {
   public:
      thing(thing_type type) : type_(type) {}
      const thing_type get_state() const { return type_; }
      const char* get_state_as_string() const {
         static const char* ttype[] = { 
               "Animal",
               "Mineral",
               "Vegetable",
               "Unknown" 
         };
         return ttype[type_];   
      }

   private:
      thing_type type_;
   };


   int main() {
      thing th(DTypeMineral);
      std::cout &lt;&lt; "this thing is a " &lt;&lt; th.get_state_as_string() &lt;&lt; std::endl;

      return 0;
   }


I am preferring to remove all the printing stuff from the class interface and use the operator&lt;&lt; overloading idea in 200_success answer like this:

#include &lt;iostream&gt;

enum thing_type
{
   DTypeUnknown,
   DTypeAnimal,
   DTypeMineral,
   DTypeVegetable
};

const char* type2string(thing_type ttype) {
   static const char* thtype[] = { 
      "Unknown",
      "Animal",
      "Mineral",
      "Vegetable"
   };
   return ttype &lt; sizeof(thtype) ? thtype[ttype] : thtype[0];   
}

std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const thing_type type) {
   os &lt;&lt; type2string(type);
   return os;
}

class thing {
public:
   thing(thing_type type) : type_(type) {}
   const thing_type get_type() const { return type_; }

private:
   thing_type type_;
};

std::ostream&amp; operator&lt;&lt;(std::ostream&amp; os, const thing&amp; th) {
   os &lt;&lt; "This is a " &lt;&lt; type2string(th.get_type());
   return os;
}

int main() {
   thing th(DTypeMineral);
   std::cout &lt;&lt; th &lt;&lt; std::endl;

   return 0;
}
Question 1: functionxxx_as_string() is used below. How else could it be more elegantly named?


How about:

std::ostream&amp; operator&lt;&lt;(std::ostream&amp; str, thing const&amp; data);



  Question 2: Is the static char* array method adopted below the only solution? Best solution? Any suggestions?


You will need a static char array (or equivalent (like a switch)) somewhere as there is no built in way to convert enum values (which are integers) to a string.