dynamic classes and duck typing

Steven Schveighoffer schveiguy at yahoo.com
Tue Dec 1 11:06:17 PST 2009


On Tue, 01 Dec 2009 13:50:38 -0500, Andrei Alexandrescu  
<SeeWebsiteForEmail at erdani.org> wrote:

> Steven Schveighoffer wrote:
>> On Sat, 28 Nov 2009 18:36:07 -0500, Walter Bright  
>> <newshound1 at digitalmars.com> wrote:
>>
>>> And here it is (called opDispatch, Michel Fortin's suggestion):
>>>
>>> http://www.dsource.org/projects/dmd/changeset?new=trunk%2Fsrc@268&old=trunk%2Fsrc@267
>>  I have a few questions:
>>  1. How should the compiler restrict opDispatch's string argument?   
>> i.e. if I implement opDispatch, I'm normally expecting the string to be  
>> a symbol, but one can directly call opDispatch with any string (I can  
>> see clever usages which compile but for instance circumvent const or  
>> something), forcing me to always constrain the string argument, i.e.  
>> always have isValidSymbol(s) in my constraints.  Should the compiler  
>> restrict the string to always being a valid symbol name (or operator,  
>> see question 2)?
>
> Where in doubt, acquire more power :o). I'd say no checks; let user code  
> do that or deal with those cases.

It is unlikely that anything other than symbols are expected for  
opDispatch, I can't think of an example that would not want to put the  
isValidSymbol constraint on the method.

An example of abuse:

struct caseInsensitiveWrapper(T)
{
    T _t;
    auto opDispatch(string fname, A...) (A args)
    {
       mixin("return _t." ~ toLower(fname) ~ "(args);");
    }
}

class C { int x; void foo(); }

caseInsensitiveWrapper!(C) ciw;
ciw._t = new C;
ciw.opDispatch!("x = 5, delete _t, _t.foo")();

I don't know if this is anything to worry about, but my preference as an  
author for caseInsensitiveWrapper is that this last line should never  
compile without any special requirements from me.

>
>> 2. Can we cover templated operators with opDispatch?  I can envision  
>> something like this:
>>  opDispatch(string s)(int rhs) if(s == "+") {...}
>
> How do you mean that?

Isn't opBinary almost identical to opDispatch?  The only difference I see  
is that opBinary works with operators as the 'symbol' and dispatch works  
with valid symbols.  Is it important to distinguish between operators and  
custom dispatch?

-Steve



More information about the Digitalmars-d mailing list