Help with Template Code

Jarrett Billingsley kb3ctd2 at yahoo.com
Sat Mar 31 08:40:04 PDT 2007


"John Demme" <me at teqdruid.com> wrote in message 
news:eukjpj$opg$1 at digitalmars.com...
>>
>> Wow!
>>
>> struct S
>> {
>>     int x;
>>     float y;
>>     char[] z;
>>
>>     static S opCall(typeof(S.tupleof) args)
>>     {
>>         S s;
>>
>>         foreach(i, arg; args)
>>             s.tupleof[i] = arg;
>>
>>         return s;
>>     }
>> }
>>
>> void main()
>> {
>>     S s = S(1, 2.3, "hi");
>>     writefln(s.x);
>>     writefln(s.y);
>>     writefln(s.z);
>> }
>>
>> I really didn't think I would be able to write that.
>
> Ahh!!! typeof!  That does it for me... much thanks.  BTW, with your 
> example
> 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);
} 




More information about the Digitalmars-d-learn mailing list