To use opDispatch

BCS none at anon.com
Sun May 23 12:17:44 PDT 2010


Hello BCS,

> Hello bearophile,
> 
>> I have seen this bug report:
>> http://d.puremagic.com/issues/show_bug.cgi?id=4224
>> Do you know any way to make the following code work? It can be
>> useful,
>> especially once the int type can be replaced with a good variant
>> type:
>> struct A {
>> int[string] table;
>> int opDispatch(string s)() {
>> return table[s];
>> }
>> void opDispatch(string s)(int x) {
>> table[s] = x;
>> }
>> }
>> void main() {
>> A a;
>> a.i = 10;
>> assert(a.i == 10);
>> }
> IIRC I got more or less what you want somewhere in here:
> 
> http://dsource.org/projects/scrapple/browser/trunk/units/si2.d
> 
> I'll see if I can chop it down a bit.
> 

I guess I didn't rememeber correctly. Anyway, this work:


import std.stdio;

template If(bool b, T, F) { static if(b) alias T If; else alias F If; }

struct S
{
   int[string] vals;
   template opDispatch(string s)
   {
   If!(T.length == 1, void, int) opDispatch(T...)(T t)
   {
      static if(T.length == 1) vals[s] = t[0];
      else return vals[s];
   }
   }
}

void main()
{
  S s;
  s.foo = 5;
  writef("%s\n", s.foo());
}

-- 
... <IXOYE><





More information about the Digitalmars-d mailing list