Open Methods: From C++ to D

Jean-Louis Leroy via Digitalmars-d-announce digitalmars-d-announce at puremagic.com
Wed Aug 30 08:59:32 PDT 2017


On Wednesday, 30 August 2017 at 15:42:09 UTC, jmh530 wrote:
> One thing you didn't really cover is how seamlessly interacts 
> with normal polymorphism. For instance, what if to your first 
> example, I add the following function (note: without @method) 
> and adjust main as below. I see no reason why this shouldn't 
> work. But you wouldn't be able to create a string kick(Animal 
> animal) function since that is created by the mixin.
>
> string kick(Dog dog) { return "ct bark"; }
>
> void main()
> {
>   updateMethods();
>   import std.stdio : writeln;
>   Animal snoopy = new Dog, hector = new Pitbull;
>   writeln("snoopy.kick(): ", snoopy.kick()); // bark
>   writeln("hector.kick(): ", hector.kick()); // bark an dbite
>   Dog lassie = new Dog;
>   writeln("lassie.kick(): ", lassie.kick()); // ct bark
> }

What happens here is that kick(Animal) is shadowed by kick(Dog). 
kick(Animal) is a method but it appears to the user and the 
compiler as an ordinary function - which is generally good. As 
such it is eligible for UFCS. I would not recommend this sort of 
coding, but it's everyone's choice, methods or not.

Likewise, methods can be overloaded (like here 
https://github.com/jll63/openmethods.d/blob/1.0.0-rc.1/examples/matrix/source/matrix.d#L12).

A current limitation is that default arguments are not supported 
(yet), although I think it's just a matter of putting the effort 
in.

UFCS interacts nicely with methods because you can say a.plus(b) 
even if 'plus' is an open method.




More information about the Digitalmars-d-announce mailing list