how to achieve C's Token Pasting (##) Operator to generate variable name in D?

Ali Çehreli acehreli at yahoo.com
Sun May 31 09:37:24 UTC 2020


On 5/31/20 2:26 AM, Ali Çehreli wrote:

> Unfortunately, I could not reach the following cleaner syntax with a 
> mixin template:
> 
>    mixin RW!int.x;

Ok, I solved that too with a very convoluted "eponymous mixin template 
opDispatch." :)

struct RW(T) {
   template opDispatch(string name) {
     static codeImpl() {
       import std.format;

       return format!q{
         private %s _%s;
         public auto %s() { return _%s; }
         public auto %s(%s val) { _%s = val; return this; }
       }(T.stringof, name,
         name, name,
         name, T.stringof, name);
     }

     mixin template opDispatch(alias code = codeImpl()) {
       mixin (code);
     }
   }
}

struct Point {
   mixin RW!int.x;    // <-- NICE :)
   mixin RW!int.y;
     // etc.
}

import std.traits;
import std.stdio;

void main() {
   pragma(msg, FieldNameTuple!(Point));

   auto p = Point(1, 2);
   p.x = 42;
   p.y = 43;
   writeln(p);
}

Ali



More information about the Digitalmars-d-learn mailing list