可选 class-代码生成依赖于 haxe 中泛型实现的函数
Optional class-code generation in dependence of functions implemented by generics in haxe
假设我在 Haxe 中有以下 classes:
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 函数添加到对 class,当且仅当泛型 U 和 V 都实现了 hashCode 函数 ...可以通过元编程将两个 classes 组合成一个。
您只需切换到 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。
假设我在 Haxe 中有以下 classes:
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 函数添加到对 class,当且仅当泛型 U 和 V 都实现了 hashCode 函数 ...可以通过元编程将两个 classes 组合成一个。
您只需切换到 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。