预处理器宏调用所有可能的组合

时间:2018-05-14 14:11:25

标签: c++ c-preprocessor boost-preprocessor

我创建了一个带有3个条件的宏(例如,在我的实例中为8个):

#define FOO(A,B,C) \
  BOOST_PP_IF(A, a1, a2) \
  BOOST_PP_IF(B, b1, b2) \
  BOOST_PP_IF(C, c1, c2)

这正如我所料。现在我想扩展所有可能性:

FOO(0,0,0)
FOO(0,0,1)
FOO(0,1,0)
FOO(0,1,1)
FOO(1,0,0)
FOO(1,0,1)
FOO(1,1,0)
FOO(1,1,1)

通过这种方式,我必须写8行。在我的实际情况中,我必须写256行。

如何使用(boost)预处理器工具直接生成它?

MCV示例,构造函数声明类Foo接近我的实际问题:

#define WRITE_FOO(A,B,C) \
  Foo(int a1 BOOST_PP_COMMA_IF(A) BOOST_PP_IF(A, int a2, BOOST_PP_EMPTY()),
           double b1 BOOST_PP_COMMA_IF(B) BOOST_PP_IF(B, double b2, BOOST_PP_EMPTY()),
           bool c1 BOOST_PP_COMMA_IF(C) BOOST_PP_IF(C, bool c2, BOOST_PP_EMPTY()));

然后

class Foo {
  public:
    WRITE_FOO(0,0,0)
    WRITE_FOO(0,0,1)
    WRITE_FOO(0,1,0)
    WRITE_FOO(0,1,1)
    WRITE_FOO(1,0,0)
    WRITE_FOO(1,0,1)
    WRITE_FOO(1,1,0)
    WRITE_FOO(1,1,1)
  private:
    int a_1;
    int a_2;
    double b_1;
    double b_2;
    bool c_1;
    bool c_2;
};

扩展到

class Foo {
  public:
    Foo(int a1, double b1, bool c1);
    Foo(int a1, double b1, bool c1, bool c2);
    Foo(int a1, double b1, double b2, bool c1);
    Foo(int a1, double b1, double b2, bool c1, bool c2);
    Foo(int a1, int a2, double b1, bool c1);
    Foo(int a1, int a2, double b1, bool c1, bool c2);
    Foo(int a1, int a2, double b1, double b2, bool c1);
    Foo(int a1, int a2, double b1, double b2, bool c1, bool c2);
  private:
    int a_1;
    int a_2;
    double b_1;
    double b_2;
    bool c_1;
    bool c_2;
};

实施类似于:

#define IMPLEMENT_FOO(A,B,C) \
  Foo::Foo(int a1 BOOST_PP_COMMA_IF(A) BOOST_PP_IF(A, int a2, BOOST_PP_EMPTY()),
           double b1 BOOST_PP_COMMA_IF(B) BOOST_PP_IF(B, double b2, BOOST_PP_EMPTY()),
           bool c1 BOOST_PP_COMMA_IF(C) BOOST_PP_IF(C, bool c2, BOOST_PP_EMPTY())): \
    a_1(a1), \
    a_2(BOOST_PP_IF(A, a2, a1)), \
    b_1(b1),
    b_2(BOOST_PP_IF(B, b2, b1)), \
    c_1(c1),
    c_2(BOOST_PP_IF(C, c2, c1)) \
{}

2 个答案:

答案 0 :(得分:2)

这是解决问题的线性代码解决方案(虽然我不建议在实际代码中执行此操作,但如果可能,请使用template

#define W2(...) W1(__VA_ARGS__,0) W1(__VA_ARGS__,1)
#define W1(...) W0(__VA_ARGS__,0) W0(__VA_ARGS__,1)
W2(0) W2(1)

Try it online!

答案 1 :(得分:0)

不直接回答您的问题(这不使用宏),但您可以使用模板元编程来解决您的问题。

不幸的是,variadic模板是C ++ 11的一个特性。 This question包含有关如何使用纯C ++实现C ++ 03或使用Boost this question实现它们的更多详细信息。

还需要线性代码。

struct F{
    int i1,i2,d1,d2;

    template<class... Args>
    F(Args... args){init(args...);}

    void init(){} // base case
    template<class... Args>
    void init(int i1_,Args... args){i1=i1_;i2=i1_;init(args...);}
    template<class... Args>
    void init(int i1_,int i2_,Args... args){i1=i1_;i2=i2_;init(args...);}
    template<class... Args>
    void init(double d1_,Args... args){d1=d1_;d2=d1_;init(args...);}
    template<class... Args>
    void init(double d1_,double d2_,Args... args){d1=d1_;d2=d2_;init(args...);}

};

Try it online!(gcc)或Try it online!(clang)

要求类型可分配。如果您担心效率,可能需要添加一些std::move

相关问题