__traits(allMembers, T)
返回实例成员和静态成员。如何筛选出静态成员?我希望这对领域和方法都有效。
当然可以。D的内省能力是巨大的,在你的情况下,来自std.meta
的Filter是你的朋友;-(
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);
}