使用C预处理程序遍历结构字段 [英] Use C preprocessor to iterate over structure fields

查看:76
本文介绍了使用C预处理程序遍历结构字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个具有相同名称字段的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.

推荐答案

如果您已经拥有Boost依赖项,则可以使用

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆