如何使用宏来收集变量名? [英] How can I use a macro for collecting variable names?

查看:109
本文介绍了如何使用宏来收集变量名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想简化以下

class A {
    int a;
    int b;
    int c;
    std::vector<int*> addrs;
public:
    A() : addrs{ &a, &b, &c } {}
};

,因此我没有在两个地方写字段列表,即声明和 addrs 的初始化程序。是否有一些方法使用宏来收集声明并在以后使用它们。例如,

so that I don't have the write the list of fields in two places, i.e. the declarations and the initializer for addrs. Is there some way to use a macro to collect the declarations and use them later. E.g.,

class A {
    VAR_DECL(a);
    VAR_DECL(b);
    VAR_DECL(c);
    std::vector<int*> addrs;
public:
    A() : addrs{ VAR_ADDRESSES } {}
};

对于上下文,这是为了实现某种属性内省系统。

For context this is intended for implementing some kind of property introspection system.

推荐答案

您可以使用 Boost预处理器

#define VARIABLES (a)(b)(c)

#define DECLARE_MEMBER(maR, maType, maId) \
  maType maId;

#define TAKE_ADDRESS(maR, maUnused, maIndex, maId) \
  BOOST_PP_COMMA_IF(maIndex) & maId

class A {
  BOOST_PP_SEQ_FOR_EACH(DECLARE_MEMBER, int, VARIABLES)
  std::vector<int*> addrs;
public:
  A() : addrs { BOOST_PP_SEQ_FOR_EACH_I(TAKE_ADDRESS, %%, VARIABLES) } {}
};

// Now you can clean up:
#undef DECLARE_MEMBER
#undef TAKE_ADDRESS
// In case you no longer need the list, also:
#undef VARIABLES

这篇关于如何使用宏来收集变量名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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