簡體   English   中英

C ++宏元編程

[英]C++ macro metaprogramming

我有以下代碼:

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;});
}

這些方法僅在運算符符號上有所不同。 有沒有辦法簡化使用宏編寫這些方法?

是的,這很容易:

#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(/)

當然,如果您需要多次重復使用此運算符符號列表,可以使用X宏技巧:

operators.hxx

OPERATOR(+)
OPERATOR(-)
OPERATOR(*)
OPERATOR(/)

#undef OPERATOR

你的代碼

#define OPERATOR(OP) \
  /* same as above */

#include "operators.hxx"

看起來很瑣碎?

#define D(O) \
    Vec& Vec::operator O ## = (const double x) \
    { return apply([x](double y) {return x O y;}); }

D(+)
D(-)
D(*)
D(/)

#undef

## “將”參數粘合到= ,你需要它,因為+=-=等等是原子標記。 其余的都是由宏的魔力處理。

證明它編譯

順便說一句,你所有的操作員都錯了; 他們應該閱讀y O x ,而不是x O y

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM