【问题标题】:haxe operator overloading ==, Class not found error for template parametershaxe 运算符重载 ==,模板参数找不到类错误
【发布时间】:2013-12-13 20:41:49
【问题描述】:

我正在尝试在自定义“对”类型上重载等于 (==) 运算符,如下所示:

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;

}

我是抽象类和运算符重载的新手。但是重载部分几乎是从 haxe 文档示例中逐字复制的。重载运算符旨在测试两对的相等性。但是,当我将代码编译到 neko 时,出现错误:

Pair.hx:11: lines 11-13 : Class not found : A

我在这里感到困惑,因为正如您在重载函数上方看到的那样,有一个普通函数版本“equals1”,它编译得很好。只要我添加@:op(X == Y),Pair 中的模板参数A 就是“未找到”。

我的问题是如何使这种重载工作,我的代码出了什么问题?

提前致谢。

附:我正在使用安装在 Windows 上的 Haxe Compiler 3.0.1。

--更新--: 我再次查看了代码,似乎将equals函数声明为“静态”导致了问题。如果我在普通函数中添加“静态”,

static public function equals1(lhs:Pair<A,B>, rhs:Pair<A,B>):Bool { 
 ...

报同样的错误。

--更新--: 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);

}
}

输出: Main.hx:34: 假 Main.hx:35: 真

【问题讨论】:

    标签: operator-overloading haxe


    【解决方案1】:

    这里的问题是在类/抽象上声明的类型参数的范围是实例/值,因此没有在静态上下文中定义。

    因此,需要对函数进行参数化:

    @:op(X == Y) static public function equals1<A, B>(lhs:Pair<A,B>, rhs:Pair<A,B>):Bool;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-27
      • 2021-02-17
      • 1970-01-01
      • 2020-02-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多