我正在尝试使用以下代码从类中获取完整数据成员的列表:
import std.stdio;
import std.traits;
class D
{
static string[] integralMembers = getIntegralMembers();
static string[] getIntegralMembers()
{
auto allMembers = __traits(allMembers, D);
string[] tmp = new string[allMembers.length];
int ct = 0;
for(int i = 0; i != allMembers.length; ++i) {
bool isInteg = __traits(isIntegral, __traits(getMember, D, allMembers[i]));
if(isInteg) {
tmp[ct++] = allMembers[i];
}
}
string[] ret = new string[ct];
for(int i = 0; i != ct; ++i) {
ret[i] = tmp[i];
}
return ret;
}
int a;
this() { }
~this() { }
}
void main()
{
auto integralMembers = D.integralMembers;
foreach(mem; integralMembers)
{
writeln(mem);
}
}
但是,编译失败并出现以下错误:
main.d(17): Error: variable i cannot be read at compile time
main.d(17): Error: expression expected as second argument of __traits getMember
main.d(19): Error: variable i cannot be read at compile time
main.d(7): called from here: getIntegralMembers()
如何使此代码编译?