inout, delegates, and visitor functions.

Sebastien Alaiwan via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Oct 24 04:28:15 PDT 2015


Hi ponce,
Thanks for your suggestion.
I think I may have found the beginning of a solution:

class E
{
   import std.traits;

   void apply(this F, U)(void delegate(U e) f)
     if(is(Unqual!U == E))
   {
     f(this);
   }

   int val;
}

int main()
{
   void setToZero(E e)
   {
     e.val = 0;
   }

   void printValue(const E e)
   {
     import std.stdio;
     writefln("Value: %s", e.val);
   }

   E obj;

   obj.apply(&setToZero);
   obj.apply(&printValue);

   const(E) objConst;
   //objConst.apply(&setToZero);
   objConst.apply(&printValue);

   return 0;
}


Basically, I avoid the 'const'/'inout' attribute of the 'apply' 
function by using a 'this F' template argument.
Then, I need a second template argument 'U', otherwise, I can't 
call 'printValue' on a non-const E instance.




More information about the Digitalmars-d-learn mailing list