jll63 / openmethods.d

Open multi-methods for the D language. OPEN! Multi is cool. Open is great.
44 stars 8 forks source link

How is different than UFCS? #4

Closed TurkeyMan closed 7 years ago

TurkeyMan commented 7 years ago

Please clarify how all this effort is different than UFCS so interested parties can understand why at a glance? D has UFCS, I don't understand how this is different...

jll63 commented 7 years ago

UFC is a compile time mechanism, like overload resolution. It uses the static type of the "receiving" object. Open methods are resolved at run time, like virtual functions:

import std.stdio;

import openmethods;
mixin(registerMethods);

class Dog {}
class Pitbull : Dog {}

string kick(virtual!Dog);

@method
string _kick(Dog x)
{
  return "bark";
}

@method
string _kick(Pitbull x)
{
  return next!kick(x) ~ " and bite";
}

string kickUFC(Dog x)
{
  return "bark";
}

string kickUFC(Pitbull x)
{
  return next!kick(x) ~ " and bite";
}

void main()
{
  updateMethods();

  Dog rex = new Pitbull;
  writeln(kick(rex)); // bark and bite
  writeln(rex.kickUFC()); // just bark
}