假设我在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;
}
}
我想知道是否可以编写一个宏将哈希码函数添加到对等级时,并且仅当generics u和v都实现HashCode-unction时,因此可以将两个类组合起来。通过元编程进入一个。
您可以通过简单地切换到摘要来实现所需的行为:
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
的必要约束。
有关完整的典范,请查看尝试HAXE#D76E1。