To use opDispatch

Simen kjaeraas simen.kjaras at gmail.com
Sun May 23 13:14:30 PDT 2010


bearophile <bearophileHUGS at lycos.com> wrote:

> But have you tried to run it? That is similar to one of my first  
> versions, and it doesn't work, I don't know why.

You're right. Property syntax is what causes it. It only
instantiates the template with the parameter for the name.[1]


This code seems to work correctly:

struct bar {
   int[string] table;

   template opDispatch( string name ) {
     @property
     auto opDispatch( T... )( T args ) {
       static if (T.length == 0) {
         return table[name];
       } else static if (T.length == 1) {
         table[name] = args[0];
       } else {
         pragma( msg, to!string( T.length ) );
         static assert(false, "Wrong parameter count to opDispatch");
       }
     }
   }
}

void main( ) {
   bar b;
   b.foz = 34;
   writeln( b.foz( ) );
}

Note however, that property syntax does not work for the degenerate case
of 0 arguments, i.e. the getter. One has to call it without the benefit
of property syntax.

[1]: http://d.puremagic.com/issues/show_bug.cgi?id=620

-- 
Simen


More information about the Digitalmars-d mailing list