declarations as template parameters

Daniel N via Digitalmars-d digitalmars-d at puremagic.com
Sun Aug 30 13:08:56 PDT 2015


On Sunday, 30 August 2015 at 18:43:32 UTC, Adam D. Ruppe wrote:
> On Sunday, 30 August 2015 at 16:31:17 UTC, Daniel N wrote:
>> I guess it could be possible to solve using UDA:s instead... 
>> maybe I'll try that next, just checking if I'm the only one 
>> dreaming about "declarations as template parameters".
>
> What I would love would be being able to pass an anonymous 
> struct to a template. Then you can reflect over it to get 
> declarations and group them too.
>
> (Actually, I'd love to be able to use anonymous structs 
> anywhere a typename is expected. Then you could do:
>
> struct { int a; } foo; // declare a variable named foo as type 
> struct { int a; }
>
> but that might break the parser.)

Hmmm yeah, I remember wanting that too... how about this? Passing 
an anonymous class via a function instead of template.

import std.traits;

enum codeof(S...) = S[0].stringof;

string fun(T)(T sigh)
{
   import std.typetuple;
   import std.algorithm : map;
   import std.string : format;
   import std.range : zip, join;

   alias names = FieldNameTuple!T;
   alias types = staticMap!(codeof, FieldTypeTuple!T);

   return zip([types], [names]).
          map!(a => format("  %s %s;\n", a[0], a[1])).
          join();
}

void main()
{
   struct Yay
   {
     mixin(fun(new class
     {
       int a;
     }));
   }
}


More information about the Digitalmars-d mailing list