Passing a module in a template parameter list to __traits(allMembers, module)

Ali Çehreli acehreli at yahoo.com
Tue Feb 26 11:12:05 PST 2013


On 02/26/2013 11:03 AM, Ben Gertzfield wrote:
> Hi folks,
>
> In preparation for my upcoming talk at DConf 2013, I'm working on a
> compile-time dependency injection prototype for D.
>
> I'd like part of public interface for this system to take a module at
> compile time, and return a list of the classes in that module. Something
> like:
>
> string GetMembers(T)() {
> auto members = [__traits(allMembers, T)];
> return join(result, ", ");
> }
>
> If I pass a module to __traits(allMembers, foo.bar) outside a template
> parameter list, it works great, but as soon as I pass it through a
> template parameter list, I get an odd error:
>
> Error: template instance GetMembers!(std) GetMembers!(std) does not
> match template declaration GetMembers(T)()
>
> Here's the code I'm working on. Any thoughts on whether this is
> possible, and if so, what I'm doing wrong?
>
> http://pastebin.com/BgZ67h8P
>
> Thanks,
>
> Ben

Hi Ben, I am in the same boat and I am about to post questions here 
about code problems. :)

Your first code works with three modifications:

1) std.stdio is not a type, so the template parameter list cannot be 
(T). I used 'alias'.

2) For syntax reasons, you must parenthesize (std.stdio) when passing as 
a template parameter

3) (You couldn't get to this yet.) A typo: result -> members

import std.array;
import std.stdio;
import std.traits;

string GetMembers(alias T)() {
   auto members = [__traits(allMembers, T)];
   return join(members, ", ");
}

void main() {
     stdout.writefln("Got members: %s", GetMembers!(std.stdio));
}

Ali


More information about the Digitalmars-d mailing list