__traits(allMembers, T)
返回实例和静态成员。如何过滤掉静态成员?我希望这适用于两个领域和方法。
答案 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);
}