在C ++库中,存在用户定义的类型,它将变量的符号值的文本表示添加到原始数据类型int,double,...,bool:
template<typename T>
class Var {
T value;
//a datastructure containing Expressions and string representations of operators
Expression expr;
}
addition (+)
的运算符被覆盖:
#define OVERLOAD_ARITHMETIC_OPERATOR(op, opName) \
template<typename X, typename Y>\
auto operator op(const X x, const Y y) ->\
se::Var<decltype(__filter(x).getValue() op __filter(y).getValue())> \
{\
const auto __x = __filter(x);\
const auto __y = __filter(y);\
auto result = se::constructVar(__x.getValue() op __y.getValue());\
if(__x.isSymbolic() || __y.isSymbolic()) {\
result.setExpression(BINARY_EXPRESSION(opName, __x.getExpression(), __y.getExpression()));\
}\
return result;\
}\
OVERLOAD_ARITHMETIC_OPERATOR(+, ADD)
以下计划:
main.cpp中:
#define double Double
#define int Int
#define float Float
#define bool Bool
#include "aprogram.c"
#undef double
#undef int
#undef float
#undef bool
int main(){
std::cout << afunction();
}
aprogram.c:
int afunction(){
double t1 = ... ;
double t2 = ... ;
return t1 + t2;
}
按预期返回t1.expr + t2.expr
。
问题
重载运算符greater (>)
时:
#define OVERLOAD_COND_OPERATOR(op, opName) \
template<typename X, typename Y>\
se::Var<bool> operator op(const X x, const Y y)\
{\
const auto __x = __filter(x);\
const auto __y = __filter(y);\
auto result = se::constructVar(__x.getValue() op __y.getValue());\
if(__x.isSymbolic() || __y.isSymbolic()) \
result.setExpression(BINARY_EXPRESSION(opName, __x.getExpression(), __y.getExpression()));\
return result;\
}\
OVERLOAD_COND_OPERATOR(>, GREATER)
并将 fiunction()中的返回值更改为return t1 > t2
我们期望得到类似的结果t1.expr > t2.expr
,但结果会被转换为bool并且信息存储在Var.expr丢失了。
虽然我认为+
和>
的运算符类似,但是你能帮助我理解为什么>
表现不同吗?你能帮助我达到想要的行为吗?
请提供反馈意见:帮助我帮助你。
发布后添加的信息
1 /
__filter()
是返回数据结构Var的方法。在我的示例中,Var被大大简化了,过滤器只返回包含T value
和Expression expr
的对象。
2 /
typedef se::Var<double> Double;
typedef se::Var<int> Int;
typedef se::Var<char> Char;
typedef se::Var<float> Float;
typedef se::Var<bool> Bool;