如何获得一个类型的所有非静态成员?

时间:2016-08-07 11:55:02

标签: reflection d

__traits(allMembers, T)返回实例和静态成员。如何过滤掉静态成员?我希望这适用于两个领域和方法。

1 个答案:

答案 0 :(得分:2)

当然可以这样做。 D的内省能力是巨大的,在你的情况下,来自std.meta的{​​{3}}是你的朋友;-)

struct Lion
{
    static maxSpeed = 100;
    string name;
    bool isDangerous()
    {
        return true;
    }
    static bool isAlive(uint meat)
    {
        return meat > 100;
    }
}

template FilterMembers(alias T, bool filterStatic = true)
{
    import std.meta : Filter;
    template filter(string member)
    {
        enum memberStr = T.stringof ~ "." ~ member;
        enum isStatic = __traits(isStaticFunction, mixin(memberStr)) ||
                        __traits(compiles, mixin("{auto b = " ~ memberStr ~ ";}"));
        enum filter = filterStatic ^ isStatic;
    }
    enum FilterMembers = Filter!(filter, __traits(allMembers, T));
}


unittest
{
    import std.meta : AliasSeq;
    assert(FilterMembers!Lion == AliasSeq!("name", "isDangerous"));
    assert(FilterMembers!(Lion, false) == AliasSeq!("maxSpeed", "isAlive"));
}

// or using the old-school main
version(unittest) {} else
void main()
{
    import std.stdio;
    foreach (member; FilterMembers!Lion)
        writeln(member);
}