I have the following piece of code:
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;});
}
These methods only differ in the operator symbol. Is there a way to simplify writing these methods using a macro?
Yes, it's rather easy:
#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(/)
Of course, should you need to re-use this list of operator symbols more than once, you can do it with the X macro trick:
operators.hxx
OPERATOR(+)
OPERATOR(-)
OPERATOR(*)
OPERATOR(/)
#undef OPERATOR
your code
#define OPERATOR(OP) \
/* same as above */
#include "operators.hxx"
Seems pretty trivial?
#define D(O) \
Vec& Vec::operator O ## = (const double x) \
{ return apply([x](double y) {return x O y;}); }
D(+)
D(-)
D(*)
D(/)
#undef
The ##
"glues" the argument to the =
, which you need because +=
, -=
and so forth are atomic tokens. The rest is all handled by the magic of macros.
As an aside, all your operators are wrong; they should read y O x
, not x O y
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With