tin*_*lyx 2 haxe operator-overloading
我试图在自定义"对"类型上重载equals(==)运算符,如下所示:
private typedef Data<A, B> = { a: A, b: B }
abstract Pair<A, B>(Data<A, B>) {
public var a(get, set):A;
public var b(get, set):B;
public function equals1(lhs:Pair<A,B>, rhs:Pair<A,B>):Bool {
return (lhs.a == rhs.a && lhs.b == rhs.b);
}
@:op(X == Y) static public function equals(lhs:Pair<A,B>, rhs:Pair<A,B>):Bool {
return (lhs.a == rhs.a && lhs.b == rhs.b);
}
public inline function new(a:A, b:B) this =
{ a: a, b: b };
inline function get_a():A
return this.a;
inline function get_b():B
return this.b;
inline function set_a(v:A):A
return this.a = v;
inline function set_b(v:B):B
return this.b = v;
}
Run Code Online (Sandbox Code Playgroud)
我是抽象类和运算符重载的新手.但是重载部分几乎是从haxe文档示例中逐字复制的.重载运算符旨在测试两对的相等性.但是,当我将代码编译为neko时,我收到一个错误:
Pair.hx:11: lines 11-13 : Class not found : A
Run Code Online (Sandbox Code Playgroud)
我在这里很困惑,因为你可以在重载函数的正上方看到,有一个普通的函数版本"equals1",编译得很好.只要我添加@:op(X == Y),对中的模板参数A就"找不到".
我的问题是如何使这个重载工作,以及我的代码出了什么问题?
提前致谢.
PS我正在使用安装在Windows上的Haxe Compiler 3.0.1.
--Update--:我再次查看代码,似乎声明equals函数"static"导致问题.如果我在plain函数中添加"static",
static public function equals1(lhs:Pair<A,B>, rhs:Pair<A,B>):Bool {
...
Run Code Online (Sandbox Code Playgroud)
报告了相同的错误.
--update--:back2dos的答案是正确的:
private typedef Data<A, B> = { a: A, b: B }
abstract Pair<A, B>(Data<A, B>) {
public var a(get, set):A;
public var b(get, set):B;
public function equals1(lhs:Pair<A,B>, rhs:Pair<A,B>):Bool {
return (lhs.a == rhs.a && lhs.b == rhs.b);
}
@:op(X == Y) static public function equals<A, B>(lhs:Pair<A,B>, rhs:Pair<A,B>):Bool {
return (lhs.a == rhs.a && lhs.b == rhs.b);
}
public inline function new(a:A, b:B) this =
{ a: a, b: b };
inline function get_a():A
return this.a;
inline function get_b():B
return this.b;
inline function set_a(v:A):A
return this.a = v;
inline function set_b(v:B):B
return this.b = v;
}
class Main {
static public function main() {
var p1 = new Pair(1,2), p2 = new Pair(1,5);
trace (p1 == p2);
}
}
Run Code Online (Sandbox Code Playgroud)
输出:Main.hx:34:false Main.hx:35:true
这里的问题是在类/抽象上声明的类型参数的范围是实例/值,因此没有在静态上下文中定义.
因此,您需要参数化函数:
@:op(X == Y) static public function equals1<A, B>(lhs:Pair<A,B>, rhs:Pair<A,B>):Bool;