枚举结构的成员? [英] Enumerate members of a structure?
问题描述
有没有一种方法来枚举结构的成员|在C(结构类)++或C?我需要得到成员名称,类型和值。我以前用过下面的示例code上的一个小项目,其中的变量是全局范围。我现在的问题是,一组值需要从GUI复制到一个对象,文件,以及VM环境。我可以创造另一个穷人的反射系统或希望更好的东西,我没有考虑过的。有没有人有什么想法?
编辑:我知道C ++不具有反射
工会variant_t {
unsigned int类型的用户界面;
INT I;
双D;
字符* S;
};结构pub_values_t {
为const char *名称;
工会variant_t *地址;
char类型; //'我'为int; 'U'是无符号整型; 'D'为双; 'S'是字符串
};#定义pub_v(N,T)#N(工会variant_t *)及N,T
结构pub_values_t pub_values [] = {
pub_v(somemember,D),
pub_v(somemember2,D),
pub_v(somemember3,'U'),
...
};const int的no_of_pub_vs = sizeof的(pub_values)/的sizeof(结构pub_values_t);
不言自明的,有C或C无反射++。因此,(默认)列举的成员变量没有可靠的方法。
如果你有控制你的数据结构,你可以尝试的std ::矢量<提高::任何>
或的std ::地图<的std ::字符串,提振::任何>
那么你的所有成员变量添加到矢量/图。
当然,这意味着所有的变量很可能会在堆上所以会有一个性能命中本办法。随着性病::地图的方法,这意味着你将有一种穷人的反思。
Is there a way to enumerate the members of a structure (struct | class) in C++ or C? I need to get the member name, type, and value. I've used the following sample code before on a small project where the variables were globally scoped. The problem I have now is that a set of values need to be copied from the GUI to an object, file, and VM environment. I could create another "poor man’s" reflection system or hopefully something better that I haven't thought of yet. Does anyone have any thoughts?
EDIT: I know C++ doesn't have reflection.
union variant_t {
unsigned int ui;
int i;
double d;
char* s;
};
struct pub_values_t {
const char* name;
union variant_t* addr;
char type; // 'I' is int; 'U' is unsigned int; 'D' is double; 'S' is string
};
#define pub_v(n,t) #n,(union variant_t*)&n,t
struct pub_values_t pub_values[] = {
pub_v(somemember, 'D'),
pub_v(somemember2, 'D'),
pub_v(somemember3, 'U'),
...
};
const int no_of_pub_vs = sizeof(pub_values) / sizeof(struct pub_values_t);
To state the obvious, there is no reflection in C or C++. Hence no reliable way of enumerating member variables (by default).
If you have control over your data structure, you could try a std::vector<boost::any>
or a std::map<std::string, boost::any>
then add all your member variables to the vector/map.
Of course, this means all your variables will likely be on the heap so there will be a performance hit with this approach. With the std::map approach, it means that you would have a kind of "poor man's" reflection.
这篇关于枚举结构的成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!