title: C/C++: any way to get reflective enums?
body: <p>I've encountered this situation so many times...</p>
  
  <pre><code> enum Fruit {
    Apple,
    Banana,
    Pear,
    Tomato
   };
  </code></pre>
  
  <p>Now I have <code>Fruit f; // banana</code> and I want to go from <code>f</code> to the string <code>"Banana"</code>; or I have <code>string s = "Banana"</code> and from that I want to go to <code>Banana // enum value or int</code>.</p>
  
  <p>So far I've been doing this.. Assuming the enum is in Fruit.h:</p>
  
  <pre><code>// Fruit.cpp
  const char *Fruits[] = {
   "Apple",
   "Banana",
   "Pear",
   "Tomato",
   NULL
  };
  </code></pre>
  
  <p>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.</p>
  
  <p>Is there a simple way to do what I want, where everything is in one file? Preprocessor hacks, alien magic, anything..</p>
  
  <p>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 <code>reflective enum Fruit</code>.. Not even in C++0x.</p>
  
  <p>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.</p>