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 D(O) \
Vec& Vec::operator O ## = (const double x) \
{ return apply([x](double y) {return x O y;}); }
D(+)
D(-)
D(*)
D(/)
#undef
##
"glues" =
的参数,这是你需要的,因为 +=
、-=
等等都是原子标记。剩下的全靠宏的魔力处理了。
(proof that it compiles)
顺便说一句,你所有的操作员都错了;他们应该阅读 y O x
,而不是 x O 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 macro 技巧:
operators.hxx
OPERATOR(+)
OPERATOR(-)
OPERATOR(*)
OPERATOR(/)
#undef OPERATOR
你的代码
#define OPERATOR(OP) \
/* same as above */
#include "operators.hxx"
我有如下一段代码:
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 D(O) \
Vec& Vec::operator O ## = (const double x) \
{ return apply([x](double y) {return x O y;}); }
D(+)
D(-)
D(*)
D(/)
#undef
##
"glues" =
的参数,这是你需要的,因为 +=
、-=
等等都是原子标记。剩下的全靠宏的魔力处理了。
(proof that it compiles)
顺便说一句,你所有的操作员都错了;他们应该阅读 y O x
,而不是 x O 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 macro 技巧:
operators.hxx
OPERATOR(+)
OPERATOR(-)
OPERATOR(*)
OPERATOR(/)
#undef OPERATOR
你的代码
#define OPERATOR(OP) \
/* same as above */
#include "operators.hxx"