Is there a template syntax for alias-of-member?

Bill Baxter dnewsgroup at billbaxter.com
Fri Mar 7 10:12:59 PST 2008


Russell Lewis wrote:
> Here's what I'm trying to do.  I want to build a template which takes, 
> as its first parameter, a type, and then takes one or more aliases to 
> member names.  In other words, the user of the template would write 
> something like this:
> 
> BEGIN CODE (that doesn't work)
>     struct s
>     {
>         int x;
>     }
>     void main()
>     {
>         magic_template!(s, x);
>     }
> END CODE
> 
> However, I can't figure out how to do it.  Right now, I'm stumbling 
> along with string mixins, as follows:
> 
> BEGIN CODE
>     template foo(T,string member)
>     {
>       T *of()
>       {
>         T *ret = new T;
>         mixin("ret." ~member~ "= 1;");
>         return ret;
>       }
>     }
> 
>     struct s
>     {
>       int x;
>     }
> 
>     import std.stdio;
>     void main()
>     {
>       auto tmp = foo!(s,"x").of();
>       writefln(tmp.x);
>     }
> END CODE
> 
> 
> Does anybody know of a more elegant way to do this?

I think that's about as good as it gets right now.  You could eliminate 
the .of part by making foo a function template.  You can also do some 
interesting things by deducing the type from the "x" part:
    alias typeof(mixin("ret."~member)) X;

... or maybe you need to put the whole alias expression in a string. 
I'm not quite clear on what can and can't go into a mixin.

If that's not enough, try being more specific about what you are 
actually trying to do, and maybe someone can offer a better solution.

--bb


More information about the Digitalmars-d-learn mailing list