Metaprogramming macros in C ++

I have the following code snippet:

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 differ only in the operator symbol. Is there a way to simplify writing these methods with a macro?

+6
source share
2 answers

Yes, this is pretty 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, if you need to reuse this list of operator symbols several times, 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" 
+7
source

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 

## "sticks together" the argument = , which you need, because += , -= , etc. are atomic tokens. Everything else is handled by macro magic.

( confirmation that it compiles )

Aside, all your statements are wrong; they should read y O x , not x O y .

+5
source

All Articles