Getting only the data members of a type
Ali Çehreli
acehreli at yahoo.com
Sat Mar 31 12:09:45 PDT 2012
How can I determine just the data members of a struct or class,
excluding the member functions? isCallable() comes short as member
variable that have opCall() defined are also callable:
import std.stdio;
import std.traits;
struct M
{
void opCall()
{}
}
struct S
{
int i;
M m;
void foo()
{}
}
void main()
{
foreach (member; __traits(allMembers, S)) {
if (isCallable!(mixin("S." ~ member))) {
writefln("%5s is a member function", member);
} else {
writefln("%5s is a member variable", member);
}
}
}
The output shows that S.m is a function but it is not:
i is a member variable
m is a member function <-- unexpected
foo is a member function
Wait! I found a solution before sending this message. :P isIntegral() works:
if (isIntegral!(typeof(mixin("S." ~ member)))) {
Now the output is:
i is a member function
m is a member variable <-- good but dubious
foo is a member variable
The reason is, isIntegral() specifically mentions built in types:
http://dlang.org/phobos/std_traits.html#isIntegral
<quote>
Detect whether T is a built-in integral type. Types bool, char, wchar,
and dchar are not considered integral.
</quote>
Thank you,
Ali
More information about the Digitalmars-d-learn
mailing list