Help with Template Code

Frits van Bommel fvbommel at REMwOVExCAPSs.nl
Sat Mar 31 08:56:57 PDT 2007


Jarrett Billingsley wrote:
> "John Demme" <me at teqdruid.com> wrote in message 
> news:eukjpj$opg$1 at digitalmars.com...
>> above, you could probably turn that opCall into a mixin... It'd be a nice
>> little mixin to have in Tango and/or Phobos.
> 
> template StructCtor(T)
> {
>     static T opCall(typeof(T.tupleof) args)
>     {
>         T t;
> 
>         foreach(i, arg; args)
>             t.tupleof[i] = arg;
> 
>         return t;
>     }
> }
> 
> struct s
> {
>     int x;
>     float y;
>     char[] z;
> 
>     mixin StructCtor!(S);
> } 

Come on, we can do a bit better than that!
---
template StructCtor()
{
     static typeof(*this) opCall(typeof(typeof(*this).tupleof) args)
     {
         typeof(*this) t;

         foreach(i, arg; args)
             t.tupleof[i] = arg;

         return t;
     }
}

struct S
{
     int x;
     float y;
     char[] z;

     mixin StructCtor;
}
---

There. Now you don't need to specify the type, and you get rid of the 
"!(S)" at point-of-use entirely.
I didn't know you could omit !() from a template mixin statement until I 
tried it just now, by the way. Cool.


More information about the Digitalmars-d-learn mailing list