Traits: getting all *public* members of a class?

Q q at example.com
Sat Jun 8 06:57:12 PDT 2013


Hi there, I want to iterate over all the public members of a 
class, but I've hit a stumbling block when the class resides in a 
different module and also contains private members. For example:

$ cat foo.d
class Foo {
     private int x;
     public int y;
}

$ cat main.d
import foo;

void main() {
     foreach (mem; __traits(allMembers, Foo)) {
         enum prot = __traits(getProtection, __traits(getMember, 
Foo.init, mem));
         static if (prot == "public") {
             // ...
         }
     }
}

However, the compiler gives me the following error message:

$ dmd main foo
main.d(5): Error: class foo.Foo member x is not accessible

Since I'm not interested in the private members, is there any way 
to ignore them and only iterate over the public members? Or is 
reflection in this way disallowed when the target class lives in 
a different module?


More information about the Digitalmars-d-learn mailing list