Halaman

Jumat, 25 Juli 2014

[Haxe] Operator overloading!

yep, Haxe is powerful, but every language has their own weaknesses and strengths. To do a simple class overloading, we need to declare compilers meta and using 'abstracts' which are not quite comfy.. but for the sake of knowledge.. here is a snippet to implement a simple operator overloading in haxe..

@: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...

  1. The class _MyBase needs a syntatix sugar of operator overloading, so that user could simply call _MyBase * _MyBase and use them accordingly
  2. 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..
  3. 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
  4. 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: 
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