我第一次尝试在d中使用递归模板而且我迷路了:
import std.stdio, std.conv, orange.util.Reflection;
struct Foo {
int a = 7;
int b = 4;
int c = 5;
}
void main(string[] args) {
pragma(msg,dictString!Foo);
}
template ObjDict(T) {
}
template dictString (T) {
const dictString = dictStringImpl!(T, 0);
}
template dictStringImpl (T, size_t i) {
static if(T.tupleof.length == 0)
const dictString = "";
else static if(T.tupleof.length -1 == i) {
pragma(msg, to!string("i = "~to!string(i)~" name = "~nameOfFieldAt!(T,i)));
const dictString = "dict[\"" ~ nameOfFieldAt!(T,i) ~ "\"] = " ~ nameOfFieldAt!(T,i) ~ ";";
pragma(msg,"last one "~to!string(i)~" \""~dictString~"\"");
}
else {
pragma(msg, to!string("i = "~to!string(i)~" name = "~nameOfFieldAt!(T,i)));
const dictString = "dict[\"" ~ nameOfFieldAt!(T,i) ~ "\"] = " ~ nameOfFieldAt!(T,i) ~ ";\n" ~ dictStringImpl!(T, i+1);
}
}
,编译后给出:
i = 0 name = a
i = 1 name = b
i = 2 name = c
last one 2 "dict["c"] = c;"
orange_test.d(31): Error: void has no value
orange_test.d(31): Error: incompatible types for (("dict[\"" ~ nameOfFieldAt ~ "\"] = " ~ nameOfFieldAt ~ ";\x0a") ~ (dictStringImpl!(Foo,2LU))): 'string' and 'void'
orange_test.d(31): Error: template instance orange_test.dictStringImpl!(Foo,1LU) error instantiating
orange_test.d(18): instantiated from here: dictStringImpl!(Foo,0)
orange_test.d(10): instantiated from here: dictString!(Foo)
orange_test.d(18): Error: template instance orange_test.dictStringImpl!(Foo,0) error instantiating
orange_test.d(10): instantiated from here: dictString!(Foo)
orange_test.d(10): Error: template instance orange_test.dictString!(Foo) error instantiating
orange_test.d(10): while evaluating pragma(msg, dictString!(Foo))
正如您所看到的,来自orange的nameOfFieldAt模板没有问题,但我认为递归出错了。
任何帮助都会非常感激,我很乐意让它发挥作用。
在此处查看包含相关橙色模板(以及其他一些)http://dpaste.dzfl.pl/4b7a36f8
的版本答案 0 :(得分:3)
在你的dictStringImpl模板中,你仍然使用dictString作为同名的名字:) 没有进一步看,但这将解决无效的相关错误。