C ++宏生成const结构

时间:2013-06-21 16:08:47

标签: c++ macros variadic-functions

有没有办法用其他宏生成这种宏? 例如。一个有3个成员的结构......

#define CONST_STRUCT2(name, name1, type1, name2, type2) \
    struct name \
    { \
        name(const type1& p##name1, const type2& p##name2) \
          : name1(p##name1), name2(p##name2) {} \
         const type1 name1; const type2 name2; \
    };

1 个答案:

答案 0 :(得分:0)

是的,您可以使用Boost.Preprocessor

#define CONST_STRUCT(name, members) \
  struct name \
  { \
    name(GENERATE_CTOR_PARAMS(members)) \
      : GENERATE_CTOR_INITIALISERS(members) {} \
    GENERATE_MEMBERS(members) \
  }


#define PARAM_TYPE(param) \
  BOOST_PP_TUPLE_ELEM(2, 0, param)

#define PARAM_NAME(param) \
  BOOST_PP_TUPLE_ELEM(2, 1, param)


#define GENERATE_CTOR_PARAMS(members) \
  BOOST_PP_ENUM(BOOST_PP_SEQ_SIZE(members), GENERATE_CTOR_PARAM, members)

#define GENERATE_CTOR_PARAM(z, idx, members) \
  const PARAM_TYPE(BOOST_PP_SEQ_ELEM(idx, members)) & PARAM_NAME(BOOST_PP_SEQ_ELEM(idx, members))


#define GENERATE_CTOR_INITIALISERS(members) \
  BOOST_PP_ENUM(BOOST_PP_SEQ_SIZE(members), GENERATE_CTOR_INITIALISER, members)

#define GENERATE_CTOR_INITIALISER(z, idx, members) \
  PARAM_NAME(BOOST_PP_SEQ_ELEM(idx, members)) (PARAM_NAME(BOOST_PP_SEQ_ELEM(idx, members)))


#define GENERATE_MEMBERS(members) \
  BOOST_PP_REPEAT(BOOST_PP_SEQ_SIZE(members), GENERATE_MEMBER, members)

#define GENERATE_MEMBER(z, idx, members) \
  const PARAM_TYPE(BOOST_PP_SEQ_ELEM(idx, members)) PARAM_NAME(BOOST_PP_SEQ_ELEM(idx, members));

使用示例:

CONST_STRUCT(Three, ((type1, name1))((type2, name2))((type3, name3)));

为清晰起见,省略了必要的头文件。此外,在实际应用程序中,选择更好的范围名称(例如CONST_STRUCT_GENERATE_...)。