gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 13:28:04 49 4
gpt4 key购买 nike

假设我在 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/

49 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com