我有以下代码:
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;});
}
这些方法的区别仅在于运算符。有没有一种方法可以简化使用宏编写这些方法的过程?
最佳答案
是的,这很简单:
#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(/)
当然,如果您需要多次重复使用此运算符符号列表,则可以使用X macro技巧进行操作:
operator.hxx
OPERATOR(+)
OPERATOR(-)
OPERATOR(*)
OPERATOR(/)
#undef OPERATOR
您的代码
#define OPERATOR(OP) \
/* same as above */
#include "operators.hxx"