小编Phi*_*ull的帖子

了解Mixins与Mixin模板

在学习D语言的过程中,我试图制作一个通用的Matrix类,以支持所包含对象的类型提升。

也就是说,当我将a乘以a时Matrix!(int)Matrix!(real)我应该得到Matrix!(real)一个结果。

由于类型升级有很多不同的类型,因此opBinary为每种可能的组合重新实现该方法将非常繁琐,并且会产生大量样板代码。因此,mixin / mixin模板似乎是答案。

我无法理解的是为什么第一个代码示例有效

import std.stdio;
import std.string : format;


string define_opbinary(string other_type) {
    return "
        Matrix opBinary(string op)(Matrix!(%s) other) {
            if(op == \"*\") {
                Matrix result;
                if(this.columns == other.rows) {
                    result = new Matrix(this.rows, other.columns);
                } else {
                    result = new Matrix(0,0);
                }
                return result;
            } else assert(0, \"Operator \"~op~\" not implemented\");
        }
        ".format(other_type);
}


class Matrix(T) {
    T[][] storage;
    size_t rows;
    size_t columns;
    const …
Run Code Online (Sandbox Code Playgroud)

templates d

4
推荐指数
1
解决办法
140
查看次数

标签 统计

d ×1

templates ×1