且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C / C ++:任何方式得到反射枚举?

更新时间:2023-02-02 17:32:32

这其中需要在外部文件中定义的成果。
这将是内容的 fruit.cpp

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

,这将是的水果的defs.h

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

它的工作原理,只要中的值0开始,并且连续...

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

更新:的混合使用C99,如果你需要不连续的值从理查德·彭宁顿一此解决方案。即是这样的:

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