On Friday, 26 May 2017 at 11:27:19 UTC, zakk wrote:

I have a followup question: my background is C and in Wolfram Mathematica, so my knowledge of templates is limited to trivial examples in C++, like:

template <class T>
const T& min(const T& lhs, const T& rhs)
{
    return lhs < rhs ? lhs : rhs;
}

where the template argument is a type, and the function does the same job for different types.

It seems to me that when programming in D templates are something more powerful, is it correct of thinking of them as some argument which is known at compile time? Is this misleading?

It is :) Given your example above, 'template' doesn't mean just 'type'. The whole definition is a template, i.e. that is a template function min. Or, in case of the original question, 'sort' is a template. Not just it's arguments, but it itself. But yes, templates are purely compile-time constructs. When you instantiate them with different arguments, you effectively get different functions in your code. Hence the name: compiler takes an existing definition (a template) and builds a whole new concrete function from it.

So if you were to call that C++ min function like this:

min(1, 2);

the compiler would generate a concrete function min, instantiated with T that is int, and then if you make this call:

min(1.5, 2.0);

then the compiler would generate *another* min, this time for type double. Note that double is of different size than int (i.e. usually int is 4 bytes, double is 8), and is also a floating-point type, not integral. So the compiler would have to issue different CPU instructions when generating code for it.

So now you get two different functions, but code for both of them has only been written once, the compiler takes care of the rest. Had 'min' not been a template, the programmer would have to write a new version by hand for every type needed, to get the most efficient code from the compiler.

Reply via email to