实现类似C#语言的枚举
#include <cstdlib>
#include <iostream>
using namespace std;
#define ENUMERATION(ENUMTYPE, VALUE) \
enum ENUMTYPE##_ {VALUE}; \
struct ENUMTYPE##Struct \
{ \
ENUMTYPE##_ key; \
char value[128]; \
}; \
ENUMTYPE##Struct ENUMTYPE##List[] = {{VALUE, #VALUE}}; \
class ENUMTYPE \
{ \
public: \
ENUMTYPE(ENUMTYPE##_ value) \
{ \
value_ = value; \
} \
ENUMTYPE& operator=(ENUMTYPE##_ value) \
{ \
value_ = value;\
return *this; \
} \
operator int() \
{ \
return value_; \
} \
const char* c_str() const \
{ \
return ENUMTYPE##List[value_].value;\
} \
private: \
ENUMTYPE##_ value_; \
}
ENUMERATION(COLOR, RED);
int main(int argc, char *argv[])
{
COLOR c = RED;
cout << c << ":" << c.c_str();
//system("PAUSE");
return EXIT_SUCCESS;
}
输出: 0:RED
上面通过一个枚举结构数组,实现了类似C#语言的枚举
不过上面的实现方法相当的不优雅,我的想法是实现类似BOOST库的Function方式的
Enum<Color (RED, BLACK, WHITE)> c;
c = Color::RED;
c = 1;
c = "RED";
std::cout << c << ":" << c.c_str() << "\n";
目前还没有想到怎么来实现,仅仅是一个想法,希望大家能给我提供点意见.
我想如果C++的枚举值如果能达到像上面说的,那一定是非常爽的