dynamic classes and duck typing

Chris Nicholson-Sauls ibisbasenji at gmail.com
Fri Nov 27 23:16:33 PST 2009


Walter Bright wrote:
> One thing Java and Python, Ruby, etc., still hold over D is dynamic 
> classes, i.e. classes that are only known at runtime, not compile time. 
> In D, this:
> 
>    s.foo(3);
> 
> could be emulated with:
> 
>    s.dynamicMethod("foo", 3);
> 
> Unfortunately, that makes it impossible to use s with generic code 
> (besides looking unappealing). But with a small feature, we can make 
> this work:
> 
>    struct S
>    {
>         ...
>     T opDynamic(s : string)(args...);
>    }
> 
> and then s.foo(3), if foo is not a compile time member of s, is 
> rewritten as:
> 
>    s.opDynamic!("foo")(3);
> 
> and opDynamic defers all the nuts-and-bolts of making this work out of 
> the language and into the library.
> 
> In particular, opDynamic's parameter and return types should all be 
> instances of std.variant.
> 
> (This has come up in various forms in this n.g. before, but I don't have 
> any references handy.)

Seems fine, but how will this interact with "alias...this" and opDot?  The former seems 
simple enough: if the "alias...this" field provides the member, use that, otherwise fall 
back on opDynamic.  The latter seems iffy, though.  Maybe something like this:

	// if the return type of opDot provides the member...
	(auto tmp = s.opDot, tmp ? tmp.foo(3) : s.opDynamic!"foo"(3))

Hmm... ew... but I can't think of anything better off-hand.  The "simple" design would 
probably be for opDynamic's implementation to make the call on whether to forward to 
opDot's result; aka, push the decision to the programmer.  Stick a mixin somewhere for the 
most basic case (what I showed above) and its no big deal.

-- Chris Nicholson-Sauls



More information about the Digitalmars-d mailing list