Many people know about template classes in C++. When you start working with templates, this is usually what you’re looking for. The staple of template demonstrations is the linked list class. This one is a common need from developers. The good news is that the STL libraries implement this one very well. Anyways, what many people don’t know about templates is that you can create template functions just as easily. Sometimes, you may not even know you’re calling a template function.
Let’s create a min function. It’s common to use macros, but macros don’t always maintain type-safeness.
template <class T>
T Min(T a, T b)
{
if (b < a)
return b;
else
return a;
}
You’ll notice that the first line is the same as when you’re creating a template class. And just like a template class, you just reference your template parameter normally.
However, now, we can write code like this:
int a = 5;
int b = 6;
int m = Min(a, b);
This will generate a function Min using int as a base type. And it’s type-safe. You can easily change it to:
double a = 5;
double b = 6;
double m = Min(a, b);
This will call a double version of the same function. If you wanted to do this without templates, you’d have to either (a) use macros, or (b) create 2 different functions.
The following code will generate an error:
int a = 5;
double b = 6;
int m = Min(a, b);
“error C2782: 'T Min(T,T)' : template parameter 'T' is ambiguous”
To fix the above issue, you can call Min as this instead:
int m = Min<int>(a, b);
This will disambiguate the parameters giving you a solid definition. Note that b will be casted to an int as the call commences.
You get the idea now. This is a very basic example. I always hate it when you needs to see how to use something, but they always give very basic examples which don’t show the solution to the problem you’re having. In an upcoming post, I’ll show you a much more complex solution using templates that I actually needed to develop.