Skip to main content
1 of 2
arcomber
  • 2.5k
  • 7
  • 28
  • 46

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 <iostream>
   
   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 << "this thing is a " << th.get_state_as_string() << std::endl;
   
      return 0;
   }
arcomber
  • 2.5k
  • 7
  • 28
  • 46