简体   繁体   中英

C++ macro metaprogramming

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.

( proof that it compiles )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM