d串插件中用非静态对象
import std.array;
import std.format;
public class BinaryOperatorExpression
{
private
{
string operator;
Expression firstExpr;
Expression secondExpr;
}
public final this(T)(string operator, T firstExpr, T secondExpr)
{
this.operator = operator;
this.firstExpr = firstExpr;
this.secondExpr = secondExpr;
}
override public double eval()
{
double firstOperand = firstExpr.eval();
double secondOperand = secondExpr.eval();
return mixin(
format("%d %s %d", firstOperand, operator, secondOperand)
);
}
}
T有返回double的eval,如何使firstOperand和secondOperand为静态?
eval函数块:mixin不是在这里使用的正确工具.尝试用switch语句或if-else语句重写代码.
mixin在编译时求值内容,只能在其中使用编译时数据,例如变量和模板参数enum,而操作符在编译时是未知的.
也可映射运算符到相应函数的关联数组,如下:
enum opMap =
[ "+": (double a, double b) => a+b,
"-": (double a, double b) => a-b,
//...
];
//求值函数.
return opMap[operator](firstOperand, secondOperand);
浙公网安备 33010602011771号