C宏元编程
发布时间:2020-12-16 05:26:35 所属栏目:百科 来源:网络整理
导读:我有以下代码: 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
我有以下代码:
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 macro技巧: operators.hxx OPERATOR(+) OPERATOR(-) OPERATOR(*) OPERATOR(/) #undef OPERATOR 你的代码 #define OPERATOR(OP) /* same as above */ #include "operators.hxx" (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |