Templates D语言中递归模板的问题
我第一次尝试在d中使用递归模板,但失败了:Templates D语言中递归模板的问题,templates,recursion,compiler-errors,metaprogramming,d,Templates,Recursion,Compiler Errors,Metaprogramming,D,我第一次尝试在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) {
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模板没有问题,但我认为递归中出现了一些问题
任何帮助都将不胜感激,我很想让它工作
请参阅此处,以获取具有相关橙色模板(以及其他一些模板)的版本。在dictStringImpl模板中,您仍然使用dictString作为同名名称:)
没有进一步查看,但这将修复与void相关的错误。这很简单。谢谢,现在都修好了:)