开发者

Does __traits(hasMember) work with classes?

According to the documentation, __traits(hasMember, ...) is supposed to w开发者_如何学运维ork with any type that has members, but I can't get code that uses it with classes to compile. Observe the following snippet:

struct A {
    int foo;
}

static assert(__traits(hasMember, A, "foo"));

This compiles (though it won't link because there's no main). But if I change "struct A" to "class A", the static assert fires and the code will not compile. I can't find anything in the bug tracker and it seems like this is a big E on the eye chart sort of thing. Am I doing something wrong?

--Edit: Following the example of getMember, it appears that hasMember only works on the class if foo is static. Alternatively, I can instantiate an A and test the instance with for a non-static foo. The problem is, I need to test the existence of a non-static member of a class at compile time.


After some reflection, I think this is intended behavior. It seems reasonable that hasMember should be used in conjunction with getMember, or that if hasMember is true, it must be legal to set or call that member. Obviously this makes no sense with a class--unless the field or method is static, it cannot be set or called without an instance. Perhaps an instanceHasMember trait is in order or at least a note in the docs.

For now, I use the time-tested

  is(typeof(mixin(`thing.`~member)))

to test this at compile-time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜