Bug 16485 – Add trait for determining whether a member variable is static or not
Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P1
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2016-09-10T22:32:57Z
Last change time
2018-01-05T13:27:29Z
Keywords
trivial
Assigned to
No Owner
Creator
Jonathan M Davis
Comments
Comment #0 by issues.dlang — 2016-09-10T22:32:57Z
We should probably have a trait in std.traits either for checking whether a member variable is static or for checking that it's not static. It's something that seems to have come up several times recently in D.Learn and stackoverflow. I don't know that this is the best implementation, since it was just quickly thrown together, but this would be one possible implementation:
template isStaticMember(T, string memberName)
if(__traits(hasMember, T, memberName))
{
mixin("alias member = " ~ T.stringof ~ "." ~ memberName ~ ";");
enum isStaticMember = !__traits(compiles, member.offsetof);
}
class C
{
int foo;
static int bar;
}
void main()
{
static assert(!isStaticMember!(C, "foo"));
static assert(isStaticMember!(C, "bar"));
}
But the fact that it's the offsetof property that is the key is definitely non-obvious and not something that it's reasonable to expect that your average programmer is going to think of, so putting something like this in std.traits would definitely be beneficial.