A tutorial on D templates

Peter Alexander peter.alexander.au at gmail.com
Fri Jan 13 15:28:02 PST 2012


On 13/01/12 10:48 PM, DNewbie wrote:
> I can't understand it. Why would someone need template programming. What problem does template solve?

Suppose you want to write a function to get the minimum of two integers. 
It's easy:

int min(int a, int b)
{
     return a < b ? a : b;
}

Suppose then you want to use it with floats. You now need to write 
another function.

float min(float a, float b)
{
     return a < b ? a : b;
}

Suppose you then want to use it with doubles, reals, complex numbers, 
strings etc. etc.  You would quickly get tired of writing these 
functions, and more importantly you would likely make mistakes at some 
point.

Templates allow you to solve this problem by writing the function once 
with placeholders for types:

T min(T)(T a, T b)
{
     return a < b ? a : b;
}

This will work for ints, floats, doubles... Anything that has a < 
operator will work.

There's much more you can do with templates, but that's the fundamental 
problem that they solve.


More information about the Digitalmars-d-learn mailing list