@:allow(Mimit) class _MyBase { var v: Int; public var y: Int; public function new(v: Int) { this.v = v; y = v * v; } } class _Mimit extends _MyBase{ public function test() { trace(v); } } @:forward abstract Mimit(_Mimit) from _Mimit to _Mimit { public function new(v:Int) this = new _Mimit(v); @:op(A + B) public function add(rhs:Mimit):Mimit { var t: Mimit = new Mimit(this.v + rhs.v); return t; } }let's analyze here for a momment...
- The class _MyBase needs a syntatix sugar of operator overloading, so that user could simply call _MyBase * _MyBase and use them accordingly
- Since the operator need to access 'private' member of the class we add the compiler's meta @:allow(Mimit) since the abstract Mimit will provided the overloads..
- And since the programmer will directly use the abstract class "Mimit" we declare another meta @:forward to the declaration, and telling the abstract to "implicitly" support _Mimit class on usages(fields and methods) by writing from _Mimit to _Mimit
- The from _Mimit to _Mimit basicly tells the compiler to please implicitly assign the this variable to _mimit and assign the this variable from _Mimit
There we have it, an operator overloading which works on haxe..
For the Usage:
For the Usage:
var m1: Mimit = new Mimit(10); var m2: Mimit = new Mimit(20); var m3: Mimit = m1 + m2; m3.test(); trace(m3.y);Frankly i'm not quite satisfied with things done this way.. a simple operator overloading made a bloated code base, i think i will stick to the static function..Cheers! :)
Tidak ada komentar:
Posting Komentar