1

我第一次尝试在 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))

如您所见,橙色的 nameOfFieldAt 模板没有问题,但我认为递归出现问题。

任何帮助将不胜感激,我很乐意让这个工作。

请参阅此处以获取带有相关橙色模板(以及其他一些模板)的版本http://dpaste.dzfl.pl/4b7a36f8

4

1 回答 1

3

在您的 dictStringImpl 模板中,您仍在使用 dictString 作为同名名称:) 没有进一步研究,但这将修复与 void 相关的错误。

于 2012-10-11T15:56:19.980 回答