Re: enum to string
On Sep 7, 11:03 pm, com...@panix.com (Greg Comeau) wrote:
In article <1189219005.343422.194...@o80g2000hse.googlegroups.com>,
surapong <bohe...@gmail.com> wrote:
Is there any easy way to extract the string from enum variable??
e.g. I have
enum TheEnum {ONE, TWO, THREE};
I would like to generate the array of string containing
{"ONE", "TWO", "THREE"}
Check outhttp://www.comeaucomputing.com/techtalk/#enumtostring
Along the same lines, you can in general include a file multiple times
to get different views of the same data. Here's how I do it for the
enum problem. File t.h is a "database" of enum names and enum values:
t.h:
E(ONE,1)
E(TWO,2)
E(FOUR,4)
#undef E
t.C:
#include <map>
#include <string>
#include <iostream>
// Make the enum
#define E(x,y) x = y,
enum MyEnum {
#include "t.h"
};
typedef std::map< MyEnum, std::string> EnumMap;
// Make the initializer for the map of enums to strings
#define E(x,y) EnumMap::value_type(x,#x),
EnumMap::value_type init[] = {
#include "t.h"
};
// Initialize the map
EnumMap em( init, &init[sizeof init/sizeof init[0]]);
// Demonstrate
int main(void)
{
std::cout << em[ONE] << "\n";
std::cout << em[TWO] << "\n";
std::cout << em[FOUR] << "\n";
return 0;
}