How do you use templates in D?

Andrew Pennebaker andrew.pennebaker at gmail.com
Tue Oct 18 10:56:09 PDT 2011


I'm writing a function called genArray that accepts a function gen and
returns a random array populated by calling gen(). genString builds on this
by returning genArray(&genChar). But my type signatures are wrong.

In dashcheck.d:

char genChar() {
    return cast(char) uniform(0, 128);
}

T[] genArray(T function() gen) {
    int len = uniform(0, 100);
    T[] arr = [];

    for(int i = 0; i < len; i++) {
        arr ~= gen();
    }

    return arr;
}

string genString() {
    return genArray(&genChar);
}

Trace:

dashcheck.d(17): Error: undefined identifier T
dashcheck.d(17): Error: T is used as a type
dashcheck.d(17): Error: undefined identifier T
dashcheck.d(17): Error: T is used as a type

Full code at GitHub <https://github.com/mcandre/dashcheck>

Cheers,

Andrew Pennebaker
www.yellosoft.us
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.puremagic.com/pipermail/digitalmars-d/attachments/20111018/27258961/attachment.html>


More information about the Digitalmars-d mailing list