Reflection to detect public/private/etc?

Nick Sabalausky a at a.a
Fri Aug 12 14:37:01 PDT 2011


"Adam D. Ruppe" <destructionator at gmail.com> wrote in message 
news:j242up$24so$1 at digitalmars.com...
> There's no way I've found, aside from direct access (so not via
> getMembers) and seeing it it fails to compile.
>

I just gave it a try. I think I may be hitting against a bug in 
__traits(compiles) WRT private. This is the best I could get (Using DMD 
2.054, Win):

testCheckPrivate2.d:
-----------------------------
Foo foo;
class Foo
{
    int a;
    private int b;

    void c() {}
    private void d() {}

    void e(int x) {}
    private void f(int x) {}
}


testCheckPrivate.d:
-----------------------------
import testCheckPrivate2;

template check(string name)
{
    enum check = __traits(compiles, {
        auto x = &(__traits(getMember, foo, name));
    });
}

// Any way to do this with foreach? Didn't work when I tried.
template checkMembers(members...)
{
    static if(members.length > 0)
    {
        // Check the first
        pragma(msg,
            members[0] ~ ": " ~
            (check!(members[0]) ? "true" : "false")
        );

        // Check the rest
        static if(members.length > 1)
            alias checkMembers!(members[1..$]) dummy;
    }
}

alias checkMembers!(__traits(allMembers, Foo)) dummy;

pragma( msg, "Manually checking foo.d: " );
pragma( msg, __traits(compiles, { auto x = &(foo.d); }) );
void main()
{
    foo.d();
    auto x = &(foo.b);
    auto y = &(foo.d);
}

Result:
----------------
>dmd testCheckPrivate.d testCheckPrivate2.d -c
a: true
b: false
c: true
d: true
e: true
f: true
toString: true
toHash: true
opCmp: true
opEquals: false
Monitor: false
factory: true
Manually checking foo.d:
true
testCheckPrivate.d(33): Error: class testCheckPrivate2.Foo member d is not 
accessible
testCheckPrivate.d(34): Error: class testCheckPrivate2.Foo member b is not 
accessible

Note that "auto y = &(foo.d);" fails to compile as expected, but 
__traits(compiles) claims that should compile. It works for the non-function 
members though.

I did the "auto x = &(...);" trick so I wouldn't have to deal with the 
function's params. Maybe you know how to put dummy args in and make it an 
actual function call instead of taking the func's address? That's probably 
be a pain, but maybe it would get around the bug.




More information about the Digitalmars-d-learn mailing list