dynamic classes and duck typing

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Tue Dec 1 11:02:44 PST 2009


Steven Schveighoffer wrote:
> On Tue, 01 Dec 2009 11:20:06 -0500, Denis Koroskin <2korden at gmail.com> 
> wrote:
> 
>> On Tue, 01 Dec 2009 19:02:27 +0300, Steven Schveighoffer 
>> <schveiguy at yahoo.com> wrote:
>>
>>>
>>> You are missing the point of opDispatch.  It is not runtime defined, 
>>> because the compiler statically decides to call opDispatch.  The 
>>> dynamic part of opDispatch comes if you want to do something based on 
>>> runtime values within the opDispatch function.  e.g. the compiler 
>>> doesn't decide at *runtime* whether to call opDispatch or some normal 
>>> function named quack, it's decided at compile time.  opDispatch could 
>>> be completely compile-time defined since it is a template.  But the 
>>> 'dynamicness' of it is basically no more dynamic than a normal 
>>> function which does something based on runtime values.
>>>
>>> Compare that to a dynamic language with which you can add methods to 
>>> any object instance to make it different than another object, or make 
>>> it conform to some interface.
>>>
>>
>> Well, I believe it's possible to implement the same with opDispatch 
>> (not just to any object, but to those that support it):
>>
>> void foo() {}
>>
>> Dynamic d = ..;
>> if (!d.foo) {
>>      d.foo = &foo;
>> }
>>
>> d.foo();
> 
> You could do something like this (I don't think your exact syntax would 
> work), but you could also do something like this without opDispatch.   
> But the name 'foo' is still statically decided.  Note that opDispatch 
> doesn't implement this ability for you, you still have to implement the 
> dynamic calls behind it.  The special nature of opDispatch is how you 
> can define how to map any symbol to any implementation without having to 
> explicitly use strings.  In fact, opDispatch is slightly less powerful 
> than such a method if the method uses a runtime string for dispatch.
> 
> For example, in php, I can do this:
> 
> foo($var)
> {
>    $obj->$var();
> }
> 
> The equivalent in D would be:
> 
> foo(string var)
> {
>    obj.opDispatch!(var)();
> }
> 
> This I would consider to be true runtime-decided dispatch.
> 
> -Steve

obj.dynDispatch(var);


Andrei



More information about the Digitalmars-d mailing list