Using C++ (Visual Studio). I'm trying to find a solution for converting an enum to a string. I came across X Macros (http://drdobbs.com/cpp/184401387) which seems to be a reasonable solution but I'm having a hard time getting it to work inside of a class. All the examples I've seen show everything defined outside of a class.
// ColorNames.h
X(Red, "Red"),
X(Blue, "Blue"),
...
// MyClass.h
class MyClass
{
public:
MyClass();
virtual ~MyClass();
#define X(a, b) a
enum Colors {
#include "ColorNames.h"
};
#undef X
#define X(a, b) b
char *colorNameStrings_[] = {
#include "ColorNames.h"
};
#undef X
}
The IDE chokes on the line *colorNameStrings_[] =...
I guess because you can't initialize a data member variable 开发者_开发技巧in the header file? How do I get this to work?
The problem is that you can't initialize a non static constant inside a class definition.
You would probably have to do it like that:
// MyClass.h
class MyClass
{
public:
MyClass();
virtual ~MyClass();
#define X(a, b) a
enum Colors {
#include "ColorNames.h"
};
#undef X
static const char * colorNameStrings_[];
};
And in the .cpp file:
// MyClass.cpp
#include "MyClass.h"
#define X(a, b) b
const char * MyClass::colorNameStrings_[] = {
#include "ColorNames.h"
};
#undef X
Instead of using X-Macros, consider using the Boost.Preprocessor library. The initial, one-time definition of the code generation macros takes a bit of work, but the end result is far cleaner and much easier to reuse.
I provided a basic implementation of a generic, Boost.Preprocessor-based enum-to-string-name conversion in an answer to "How to convert an enum type variable to a string?"
Use a struct like this
struct convert
{
std::map<MyEnum, std::string> mapping;
convert()
{
mapping[SOME_ENUM_VALUE] = "SomeValue";
// etc to fill map
}
std::string operator()(MyEnum enum)
{
return mapping[enum];
}
};
Then use like this:
convert c;
std::string ret = c(myenum); //calls operator()
精彩评论