metaprogramming - 依赖于 haxe 中泛型实现的函数的可选类代码生成

标签 metaprogramming haxe

假设我在 Haxe 中有以下类:

class Pair<U, V> {
    public var first:U = null;
    public var second:V = null;
    public function new(u:U, v:V) {
        this.first = u;
        this.second = v;
    }
}
class HashablePair<U:{ function hashCode():Int; }, V:{ function hashCode():Int; }> {
    public var first:U = null;
    public var second:V = null;
    public function new(u:U, v:V) {
        this.first = u;
        this.second = v;
    }
    public function hashCode():Int { // just a sample way ...
        var h1:Int = (first == null) ? 0 : first.hashCode();
        var h2:Int = (second == null) ? 0 : second.hashCode();
        return 3 * h1 + 5 * h2;
    }
}

我想知道是否可以编写一个宏,将 hashCode 函数添加到 pair 类中,当且仅当泛型 U 和 V 都实现了 hashCode 函数 ... 从而可以将这两个类结合起来通过元编程变成一个单一的。

最佳答案

只需切换到 abstract 即可实现所需的行为:

typedef Hashable = { function hashCode():Int; };

abstract HashablePair<U:Hashable,V:Hashable>(Pair<U,V>)from Pair<U,V> {
    public function new(u:U, v:V)
        this = new Pair(u, v);

    public function hashCode():Int { // just a sample way ...
        var h1:Int = (this.first == null) ? 0 : this.first.hashCode();
        var h2:Int = (this.second == null) ? 0 : this.second.hashCode();
        return 3 * h1 + 5 * h2;
    }
}

from Pair<U,V>使 Pair<U,V>转换为 HashablePair<U,V>允许,只要对 U 有必要的约束和 V受到尊重。

有关完整示例,请查看 Try Haxe #d76E1 .

关于metaprogramming - 依赖于 haxe 中泛型实现的函数的可选类代码生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47464350/

相关文章:

C++模板元编程(17以下版本,最好是11)

c++ - 通用回调

intellij-idea - IntelliJ : All Haxe compile conditionals treated as false

haxe - @:keep mean in Haxe? 是什么

haxe - OpenFL - 如何在另一个类中使用 addChild?

使用宏转换结构中整数字段的字节顺序

syntax - Go "import"语法是不是特别独特?

julia - 编写返回函数的 Julia 宏

compiler-optimization - 将 Haxe 编译为完全剥离的 cpp 目标?

flash - Haxe闪存硬件优化