C ++宏 - 处理两对括号

时间:2013-01-09 08:42:32

标签: c++ macros c-preprocessor

我需要预处理这段代码:

line (0,0) (5,5)

其中(0,0)表示开始x和y坐标,第二个(5,5)表示结束x和y坐标。

我能够使用

获取起始坐标
#define line(x1,y1)   myArray->shapes.push_back(new Line(x1,y1));

如何处理第二个括号?

2 个答案:

答案 0 :(得分:7)

如下所示:

struct LineCreator {
  LineCreator(type_of_shapes &shapes, int x1, int y1)
    : shapes_(shapes), x1_(x1), y1_(y1)
  {}
  void operator() (int x2, int y2) {
    shapes_.push_back(new Line(x1_, y1_, x2, y2));
  }
private:
  type_of_shapes &shapes_;
  int x1_, y1_;
};

#define line(x, y) LineCreator(myArray->shapes, (x), (y))

答案 1 :(得分:1)

将其更改为:

line (0,0,5,5)

现在您可以构建以下宏:

#define line(x1,y1,x2,y2)   myArray->shapes.push_back(new Line(x1,y1)); \
                            myArray->shapes.push_back(new Line(x2,y2));