Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ macro metaprogramming

Tags:

c++

macros

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?

like image 885
Igor Ševo Avatar asked Dec 04 '15 14:12

Igor Ševo


2 Answers

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"
like image 115
Angew is no longer proud of SO Avatar answered Sep 18 '22 19:09

Angew is no longer proud of SO


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.

(proof that it compiles)

As an aside, all your operators are wrong; they should read y O x, not x O y.

like image 30
Lightness Races in Orbit Avatar answered Sep 19 '22 19:09

Lightness Races in Orbit