Help with Template Code

John Demme me at teqdruid.com
Fri Mar 30 20:16:21 PDT 2007


Jarrett Billingsley wrote:

> "John Demme" <me at teqdruid.com> wrote in message
> news:eukg7o$m31$1 at digitalmars.com...
>> Hey all!
>>
>> There's a particular problem I'm trying to solve using templates.  I
>> don't see a reason that the compiler couldn't do this, but I'm not
>> certain I can do it with templates yet.
>>
>> Here's a slightly simplified pseudo-code-ish version of what I want to
>> do:
>>
>> T inst(T : struct)(T.tupleof t);
>>
>> Yes- this makes no sense, so let me describe.  I want to create a
>> templated
>> function wherein the template argument is a struct... OK, that's easy.
>> Next, I want the parameters of the function to be the types in the
>> struct. For example, if I have the following struct:
>> struct Foo {
>>        int a;
>>        float b;
>> }
>>
>> then the following call:
>> Foo f = inst!(Foo)(5, 8.26)
>> would pass the Tuple!(int,float)(5, 8.26) into the inst function.  No,
>> it's
>> not OK to add stuff so the calling code, but the inst function can be as
>> ugly as necessary.
>>
>> I feel like this should be possible, but I don't know how... Any ideas?
>>
>> Thanks
>>
>> --
>> ~John Demme
>> me at teqdruid.com
>> http://www.teqdruid.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.

I've got one more template problem, but I'm pretty sure I can't do this.  I
now want to access the names of the struct's fields so that I could, for
example, make a templated function that accepts a struct and prints
name:value pairs for all the fields.  Is there any way I can do this?  (If
so, I'm gonna be really, really impressed.)

Thanks again

-- 
~John Demme
me at teqdruid.com
http://www.teqdruid.com/


More information about the Digitalmars-d-learn mailing list