__traits(allMembers, T)
returns both instance and static members. How can I filter out the static members? I'd like this to work for both fields and methods.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Sure you can do this. D's introspection power is immense, in your case Filter from std.meta
is your friend ;-)
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);
}