C++宏元编程

Igo*_*evo 6 c++ macros

我有以下代码:

Vec& Vec::operator+=(const double x)
{
    return apply([x](double y) {return x + y;});
}

Vec& Vec::operator-=(const double x)
{
    return apply([x](double y) {return x - y;});
}

Vec& Vec::operator*=(const double x)
{
    return apply([x](double y) {return x * y;});
}

Vec& Vec::operator/=(const double x)
{
    return apply([x](double y) {return x / y;});
}
Run Code Online (Sandbox Code Playgroud)

这些方法仅在运算符符号上有所不同.有没有办法简化使用宏编写这些方法?

Rei*_*ica 7

是的,这很容易:

#define CREATE_OPERATOR(OP) \
  Vec& Vec::operator OP##= (const double x) \
  { return apply([x](double y) { return x OP y; }); }

CREATE_OPERATOR(+)
CREATE_OPERATOR(-)
CREATE_OPERATOR(*)
CREATE_OPERATOR(/)
Run Code Online (Sandbox Code Playgroud)

当然,如果您需要多次重复使用此运算符符号列表,可以使用X宏技巧:

operators.hxx

OPERATOR(+)
OPERATOR(-)
OPERATOR(*)
OPERATOR(/)

#undef OPERATOR
Run Code Online (Sandbox Code Playgroud)

你的代码

#define OPERATOR(OP) \
  /* same as above */

#include "operators.hxx"
Run Code Online (Sandbox Code Playgroud)


Lig*_*ica 5

看起来很琐碎?

#define D(O) \
    Vec& Vec::operator O ## = (const double x) \
    { return apply([x](double y) {return x O y;}); }

D(+)
D(-)
D(*)
D(/)

#undef
Run Code Online (Sandbox Code Playgroud)

##"胶水"的说法的=,你需要的,因为+=,-=等等都是原子令牌.其余的都是由宏的魔力处理.

(证明它编译)

顺便说一句,你所有的操作员都错了; 他们应该读y O x,而不是x O y.