使用C预处理程序遍历结构字段 [英] Use C preprocessor to iterate over structure fields
问题描述
我有几个具有相同名称字段的C ++结构和类,我必须经常在它们之间进行复制.我想做些类似的事情:(用卑鄙的伪代码)
I have several different C++ structs and classes with fields of the same name, that I have to copy between frequently. I would like to do something like: (in bashy pseudocode)
struct S{double a;
double b;
double c;};
class C{public: void set_a(double a);
void set_b(double b);
void set_c(double c); };
S s; C c;
#FOR F in FIELDSOF(S)
c.set_${F}(${F});
#ENDFOR
这是否是一个好主意,是否有一种方法可以滥用C ++预处理程序或C ++模板来实现这一目标?我使用g ++和clang ++.
Whether or not it a good idea, is there a way to abuse either the C++ preprocessor or C++ templates to achieve this? I use g++ and clang++.
我已经知道像MAKO这样的模板引擎,而且我也知道我可以编写一个程序来进行代码生成.如果您必须知道的话,我想使用它的目的之一就是用C ++结构填充Google protobuf.
I am already aware of templating engines like MAKO, and I'm also aware I could write a program to do code generation. If you must know, one of the things I would like to use this for is filling Google protobufs from C++ structs.
推荐答案
If you already have a Boost dependency, you can use BOOST_FUSION_ADAPT_STRUCT and use Fusion to iterate over the members. This also allows you to work with types, which is not possible in a pure preprocessor approach.
您还需要将成员函数映射到融合序列,以使其自动化.
You also will need to map member functions to fusion sequences to make that more automatic.
总而言之:只需编写一个构造函数即可.
All in all: Just write a constructor.
这篇关于使用C预处理程序遍历结构字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!