inout, delegates, and visitor functions.

ponce via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sat Oct 24 05:05:26 PDT 2015


On Saturday, 24 October 2015 at 11:28:17 UTC, Sebastien Alaiwan 
wrote:
> 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;
> }
>


Clever. It works because of const inference on template functions.
Didn't know you could use 'this' as a type.


More information about the Digitalmars-d-learn mailing list