Fully dynamic d by opDotExp overloading

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Fri Apr 17 09:59:29 PDT 2009


Steven Schveighoffer wrote:
> On Fri, 17 Apr 2009 10:32:04 -0400, Denis Koroskin <2korden at gmail.com> 
> wrote:
> 
>> On Fri, 17 Apr 2009 18:24:04 +0400, Steven Schveighoffer 
>> <schveiguy at yahoo.com> wrote:
>>
>>> On Fri, 17 Apr 2009 09:44:09 -0400, Leandro Lucarella <llucax at gmail.com>
>>> wrote:
>>>
>>>> I don't fully understand the example though. In writefln((v.qq = 5).i),
>>>> how is that B.i is assigned to 5 if the opDotExp("qq", 5) don't
>>>> propagate
>>>> the 5 to the new B()?
>>>
>>> I think it translates to
>>>
>>> opDotExp("qq") = 5
>>>
>>> Without knowing the signature of qq, how is the compiler supposed to
>>> infer that it is a property?  In fact, I think this might be a
>>> limitation of this syntax, you can't define dynamic properties.
>>>
>>> I for one, can't really see a huge benefit, but then again, I don't
>>> normally work with dynamic-type langauges.  It looks to me like a huge
>>> hole that the compiler will ignore bugs that would have been caught if
>>> the methods were strongly typed:
>>>
>>> class c
>>> {
>>>    void opDotExp(char[] methodname,...)
>>>    {
>>>       if(methodname == "mymethod")
>>>          callMyMethod();
>>>       else
>>>          throw new Exception("bad method name: " ~ methodname);
>>>    }
>>> }
>>>
>>> void foo(c myc, bool rarelySetToTrue)
>>> {
>>>    if(rarelySetToTrue)
>>>      myc.mymethud(); // compiles, will throw runtime exception
>>> }
>>>
>>> Also, how do you overload the return value?  Using this proposal, you
>>> can't have different dynamic methods that return different types.
>>>
>>> -Steve
>>
>> Here is how it could be done:
>>
>> class C
>> {
>>     auto opDot(string methodName, T... args)(T args) // opDotExp 
>> renamed to opDot
>>     {
>>         static if (methodName == "length") {
>>             return _length; // return type is size_t
>>         } else static if (methodName == "resize") {
>>             _resize(args); // return type is void
>>         }
>>     }
>> }
>>
> 
> Look! I found a way to implement this *in the current compiler*!:
> 
> class C
> {
>    size_t length()
>    {
>       return _length;
>    }
> 
>    void resize(T...)(T args)
>    {
>       _resize(args);
>    }
> }
> 
> sorry, couldn't help myself :P
> 
> -Steve

Yah, glad someone mentioned it :o). The best way is a blend - you can 
statically dispatch on some popular/heavily-used names, then rely on a 
hashtable lookup for dynamic stuff.

Andrei



More information about the Digitalmars-d mailing list