How do you use templates in D?

Ali Çehreli acehreli at yahoo.com
Tue Oct 18 12:32:17 PDT 2011


On Tue, 18 Oct 2011 13:56:09 -0400, Andrew Pennebaker wrote:

> 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);

It's a good thing that you are staying within ASCII. Otherwise there 
might be invalid UTF-8 sequences. :)

> T[] genArray(T function() gen) {

The template parameters are specified in a separate list before the 
function parameter list:

T[] genArray(T)(T function() gen) {

Now genArray is a function template with the template parameter T.

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

Add .idup to convert from char[] to immutable(char)[] (i.e. string):

    return genArray(&genChar).idup;

Or use std.exception.assumeUnique to communicate that the characters are 
not going to be mutated by somebody else:

import std.exception;
// ...
    auto result = genArray(&genChar);
    return assumeUnique(result);

Ali

P.S. There is also the digitalmars.D.learn newsgroup where this post 
would be appreciated at. ;)


More information about the Digitalmars-d mailing list