views:

386

answers:

8

I've encountered this situation so many times...

 enum Fruit {
  Apple,
  Banana,
  Pear,
  Tomato
 };

Now I have Fruit f; // banana and I want to go from f to the string "Banana"; or I have string s = "Banana" and from that I want to go to Banana // enum value or int.

So far I've been doing this.. Assuming the enum is in Fruit.h:

// Fruit.cpp
const char *Fruits[] = {
 "Apple",
 "Banana",
 "Pear",
 "Tomato",
 NULL
};

Obviously that's a messy solution. If a developer adds a new fruit to the header and doesn't add a new entry in Fruits[] (can't blame him, they have to be in two different files!) the application goes boom.

Is there a simple way to do what I want, where everything is in one file? Preprocessor hacks, alien magic, anything..

PS: This, contrary to reflection "for everything", would be really trivial to implement in compilers. Seeing how common a problem it is (at least for me) I really can't believe there is no reflective enum Fruit.. Not even in C++0x.

PS2: I'm using C++ but I tagged this question as C as well because C has the same problem. If your solution includes C++ only things, that's ok for me.

+3  A: 

What if you did something like this?

enum Fruit {
  Apple,
  Banana,
  NumFruits
};

const char *Fruits[NumFruits] = {
 "Apple",
 "Banana",
};

Then if you add a new entry to the Fruit enum, your compiler should complain that there are insufficient entries in the initializer of the array, so you would be forced to add an entry to the array.

So it protects you from having the array be the wrong size, but it doesn't help you ensure that the strings are correct.

David Grayson
Yes, but `const char *A[50] = { "A" };` works anyway. So it protects only against adding new items to Fruit without changing the array: if someone deletes a Fruit from the enum or swaps two values, the array will be desync'd.
Andreas Bonini
I think it depends on what compiler you are using, and what warnings you have turned on. Look at your compiler's options and see if you can enable a warning for incomplete initializers if it doesn't already do it.
David Grayson
I don't actually know for sure of any C/C++ compilers that generate this warning... so I might be totally wrong. If so, then it's just wishful thinking.
David Grayson
+1  A: 

As the other people answering the question have shown, there isn't really a clean ("D.R.Y.") way to do this using the C preprocessor alone. The problem is that you need to define an array of size of your enum containing strings corresponding to each enum value, and the C preprocessor isn't smart enough to be able to do that. What I do is to create a text file something like this:

%status ok
%meaning
The routine completed its work successfully.
%

%status eof_reading_content
%meaning

The routine encountered the end of the input before it expected
to. 

%

Here %'s mark delimiters.

Then a Perl script, the working part of which looks like this,

sub get_statuses
{
    my ($base_name, $prefix) = @_;
    my @statuses;
    my $status_txt_file = "$base_name.txt";
    my $status_text = file_slurp ($status_txt_file);
    while ($status_text =~ 
       m/
     \%status\s+([a-zA-Z_][a-zA-Z0-9_]*)\s*\n
     \%meaning\s*(.*?)\s*\n\%\s*\n
        /gxs) {
    my ($code, $meaning) = ($1, $2);
    $code = $prefix."_$code";
    $meaning =~ s/\s+/ /g;
    push @statuses, [$code, $meaning];
    }
    return @statuses;
}

reads this file and writes a header file:

typedef enum kinopiko_status {
    kinopiko_status_ok,
    kinopiko_status_eof_reading_content,

and a C file:

/* Generated by ./kinopiko-status.pl at 2009-11-09 23:45. */
#include "kinopiko-status.h"
const char * kinopiko_status_strings[26] = {
"The routine completed its work successfully.",
"The routine encountered the end of the input before it expected to. ",

using the input file at the top. It also calculates the number 26 here by counting the input lines. (There are twenty-six possible statuses in fact.)

Then the construction of the status string file is automated using make.

Kinopiko
Would love to know why this was downvoted. The above is taken from a working program (only the name is changed!).
Kinopiko
I think that your answer would be a lot clearer if you posted some of the Perl script. In particular, why are there '%status' and '%meaning' strings? What do they have to do with the question? Further, the 'kinopiko_' isn't clear until someone looks at your user name.
Chip Uni
There isn't much I can do about that last complaint, since if I posted the real name it would mean even less to you. I've posted a snippet of the perl parser for this.
Kinopiko
+18  A: 

This one requires the fruits to be defined in an external file. This would be the content of fruit.cpp:

#define FRUIT(name) name
enum Fruit {
#include "fruit-defs.h"
NUM_FRUITS
};
#undef FRUIT
#define FRUIT(name) #name
const char *Fruits [] = {
#include "fruit-defs.h"
NULL
};
#undef FRUIT

And this would be fruit-defs.h:

FRUIT(Banana),
FRUIT(Apple),
FRUIT(Pear),
FRUIT(Tomato),

It works as long as the values start in 0 and are consecutive...

Update: mix this solution with the one from Richard Pennington using C99 if you need non-consecutive values. Ie, something like:

// This would be in fruit-defs.h
FRUIT(Banana, 7)
...
// This one for the enum
#define FRUIT(name, number) name = number
....
// This one for the char *[]
#define FRUIT(name, number) [number] = #name
Gonzalo
That's a neat idea.
Kinopiko
I never thought of doing it that way.
Eld
A: 

Could make a class structure for it:

class Fruit { 
   int value; char const * name ; 
   protected:
   Fruit( int v, char const * n ) : value(v), name(n) {}
   public:
   int asInt() const { return value ; }
   char const * cstr() { return name ; } 
} ;
#define MAKE_FRUIT_ELEMENT( x, v ) class x : public Fruit { x() : Fruit( v, #x ) {} }

// Then somewhere:
MAKE_FRUIT_ELEMENT(Apple, 1);
MAKE_FRUIT_ELEMENT(Banana, 2);
MAKE_FRUIT_ELEMENT(Pear, 3);

Then you can have a function that takes a Fruit, and it will even be more type safe.

void foo( Fruit f ) {
  std::cout << f.cstr() << std::endl;
  switch (f.asInt()) { /* do whatever * } ;
}

The sizeof this is 2x bigger than just an enum. But more than likely that doesn't matter.

Eld
+4  A: 

A c99 way that I've found helps reduce mistakes:

enum Fruit {
  APPLE,
  BANANA
};
const char* Fruits[] = {
 [APPLE] = "APPLE",
 [BANANA] = "BANANA"
};

You can add enums, even in the middle, and not break old definitions. You can still get NULL strings for values you forget, of course.

Richard Pennington
+2  A: 

One trick I've done in the past is to add an extra enum and then do a compile time assert (such as Boost's) to make sure the two are kept in sync:

enum Fruit {
    APPLE,
    BANANA,

    // MUST BE LAST ENUM
    LAST_FRUIT
};

const char *FruitNames[] =
{
    "Apple",
    "Banana",
};

BOOST_STATIC_ASSERT((sizeof(FruitNames) / sizeof(*FruitNames)) == LAST_FRUIT);

This will at least prevent someone from forgetting to add to both the enum and the name array and will let them know as soon as they try to compile.

R Samuel Klatchko
A: 

I don't like macro solutions, in general, though I admit it's kind of difficult there to avoid them.

Personally I opted for a custom class to wrap my enums in. The goal was to offer a bit more that traditional enums (like iteration).

Under the cover, I use a std::map to map the enum to its std::string counterpart. Then I can use this to both iterate over the enum and "pretty print" my enum or initialize it from a string read in a file.

The problem, of course, is the definition, since I have to first declare the enum and then map it... but that's the price you pay for using them.

Also, I then use not a real enum, but a const_iterator pointing to the map (under the covers) to represent the enum value (with end representing an invalid value).

Matthieu M.
+1  A: 

One comment on the macro solution - you don't need a separate file for the enumerators. Just use another macro:

#define FRUITs \ 
    FRUIT(Banana), \ 
    FRUIT(Apple), \ 
    FRUIT(Pear), \ 
    FRUIT(Tomato)

(I would probably leave the commas out, though, and incorporate them into the FRUIT macro as needed.)

Hyman Rosen