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有返回doubleeval,如何使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);
posted @   zjh6  阅读(15)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示