duck!

Michel Fortin michel.fortin at michelf.com
Sat Oct 16 15:19:49 PDT 2010


On 2010-10-16 17:45:56 -0400, Andrei Alexandrescu 
<SeeWebsiteForEmail at erdani.org> said:

> unittest
> {
>      auto x = new Drawable;
>      auto a = nameone!Widget(x); // works
>      //auto b = nameone!ColoredWidget(x); // doesn't compile
>      auto c = nametwo!ColoredWidget(x);
>      c.draw(); // works
>      c.setColor(red); // throws NotImplemented during runtime
> }
> 
> "nameone" implements Kenji's current code. "nametwo" is the looser form 
> of duck typing: whatever methods match will work, and the rest are 
> implemented to throw during runtime.

What you're proposing above is just useless, and I'm honestly quite 
surprised you don't realize that.

The real duck type almost already exists in Phobos, and it's called a 
variant. The only problem with it is that it is powerless when it comes 
to calling functions without casting it's content to a type first. Make 
it so this code can run and then you'll have implemented duck typing 
for real:

	class Duck { void quack(); }
	Variant v = new Duck;
	v.quack();

Well, mostly. It could also be argued that this too should work too:

	Variant v = cast(Object)(new Duck);
	v.quack();

but that'd require runtime reflexion as part of ClassInfo.

-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/



More information about the Digitalmars-d mailing list