HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Converting enum values to strings in C++

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
valuesconvertingenumstrings

Problem

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 

   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;
   }


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

```
#include

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

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

std::ostream& operator<<(std::ostream& os, const thing_type type) {
os << 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& operator<<(std::ostream& os, const thing& th) {
os << "This is a " << type2string(th.get_type());
return os;
}

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

Solution

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

How about:

std::ostream& operator<<(std::ostream& str, thing const& 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.

Code Snippets

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

Context

StackExchange Code Review Q#31136, answer score: 4

Revisions (0)

No revisions yet.