Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can someone explain D language template shorthand form?

Tags:

d

I have a professor that wrote all his examples for D templates in shorthand:

T exec(alias f,T)(T t) {
    return f(t);
}

I can't find any examples that explain what this means. Can someone here explain it?

like image 209
David Mulder Avatar asked Dec 07 '12 02:12

David Mulder


2 Answers

In a function template, the first set of parens hold the template arguments and the second set holds the function arguments.

http://dlang.org/template.html#function-templates

You could rewrite that as:

template exec(alias f, T) {
    T exec(T t) {
         return f(t);
    }
}

At the usage point, if a template member has the same name as the template itself, you don't have to write it twice. This is called the eponymous trick. http://www.bing.com/search?q=eponymous+trick+d+programming+language&qs=n&form=QBRE&pq=eponymous+trick+d+programming+languag&sc=0-0&sp=-1&sk=

Though most D code I've seen uses the shorter format - the long template syntax is pretty rare for functions, classes, or structs, which can do it too: struct Foo(T) { } is a struct template with argument T.

The arguments themselves in this exec template are "alias f", which is any symbol you decide to pass it, e.g., a function or variable name, and "T", just any generic type. The repeated T are references to that type.

At the usage point, you'll most likely see it like this:

int foo(int a) { return a; } // just a regular function
exec!(foo)(10); // instantiates the template with arguments (foo, int), and then calls the function.

The second template argument here is figured out implicitly by the function arguments. This is very common with function templates: a lot of the template arguments are implicit so you rarely see them written out. You might see this referenced in D discussions as "IFTI", which means "implicit function template instantiation".

like image 191
Adam D. Ruppe Avatar answered Oct 29 '22 17:10

Adam D. Ruppe


T exec(alias f,T)(T t) {
    return f(t);
}

Here’s a shorthand template function. The « normal way » to write it is:

template exec(alias f, T) {
    T exec(T t) {
        return f(t);
    }
}

In D, if a symbol in a template scope has the same name the template itself has, you can use it as the template (it’s sorta an alias).

Then, the alias template parameter means that it can be anything – any symbol. Here, it can be a delegate, a function, a fonctor, anything. It could even be a string if your teacher used the std.functional.unaryFun.

The T parameter, like in C++, is just a type symbol.

That function just applies a functor. Here’s a strongest version :

https://github.com/D-Programming-Language/phobos/blob/master/std/functional.d#L39

like image 32
phaazon Avatar answered Oct 29 '22 16:10

phaazon