简体   繁体   English

C ++宏元编程

[英]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: 当然,如果您需要多次重复使用此运算符符号列表,可以使用X宏技巧:

operators.hxx 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 . 他们应该阅读y O x ,而不是x O y

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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