The basic idea behind templates ? Its been done before !!

The word definition of template is “something that serves as a model / pattern

Patterns …. hmmmm ….. Ever heard of patterns in software? The idea behind patterns is that no software is totally unique. The same way all cars have a steering and a set of tires, most software also have similar pieces that constitute to make them.

If you have to acceept user input, thats been done before. If you have to sort, thats been done before. If you want to use a hash, thats been done too. The only difference in a new piece of software is the way all these common stuff is put together. So why re-invent the wheel ….err sort ?

The inspiration !!!

So lets say you have written a sort program in C to sort an array of integers. And lets say you have used Binary Search, which is infamously hard to get right. After all those fixes and tests, you have an efficient fast implementation of Binary Sort.

Just as were about to finish the task, the requirements change and now you get an array of structures which should be sorted instead of using integers. Oops !!! Wouldnt it be easy, to instead have some way of encasulating that simple logic behind the binary sort and have it used for all types of data types? That way we could save a lot of time whenver we created new code / modified existing ones.

This thought is the inspiration behind templates. Almost all advanced languages give this facility. (java and c# only recently acquired this)

Logic vs Data

Give a thought about how you would make this logic reusable

int AddNumbers (int a, int b)
{
return a + b;
}

There is a way in C++ to achieve this without templates, using overloaded functions

int Add(int a, int b) {return a + b;}
char Add (char a, int b) {return a + b;}
double Add (double a, double b) {return a + b;}

You get the idea. Once we write enough number of overloaded functions, (imagine the pain !!) you could write something that simply called Add(x,y) and the right type of function would get invoked.

The realization, is that the type of the data is an important constraint, when creating reusable logic. Even if the logic is reusable, since the data type is different, statically compiled languages like C and C++ are forced to create multiple versions of the same code to satisfy compiler requirements.

Wouldn’t it be cool if the compiler does this for you and save all that trouble of defining and creating many such overloaded functions?

Enter templates …

template <class T>

T Add(T a, T b) {return a+b;}

Thats it. This will work EXACTLY LIKE THE OVERLOADED function shown above.

There will be many versions of function Add() created inside your binary like in an overloaded function

What then is the difference between an overload and a template ?

When you use a template, the compiler is intellignet enough to make a first pass through your code, to find, what versions of the overloaded function template (from now on simply referred to as the template) you require.

So if you have invoked Add with double as it’s parameter, the compiler will EMIT code, replacing the word double wherever the Type T is used inside the the template of the function Add. If it encounters Add with say, a structure type used as parameter, it will EMIT the Add template code, with the structure type used in place of the Type T keyword.

In C++ Templates is purely a compiler technology

As you can see, templates are created by creating copies of the real logic, by substituting the type used in the algorithm, with the one actually passed in, much like a programmer would copy paste his original code with the changed types. This code is then compiled along with other regular code and voila your program magically has all the overloaded definitions of the logic, it requires.

Templates vs Overloads

Though template is implemented as overloads, the basic difference is that templates are compiler generated. Therefore it knows which overloads are required and only generates those types.

So for example if program A includes the Add template and only uses it for computing integers, there would be only one overloaded form of Add created in the program. if program B computes both int and doubles, two of these would be created by the compiler. As you can see, templated code are “instantiated” based on the source code that uses it.

But overloads have to be pre-created if you want to use them and most importantly, someone should have created them before by hand (buggy + painful) if it should work – not so cool or easy to use if you ask me

Any more uses ?

Let me spell this out, if you missed the idea – but templates are actually creating new code. CODE GENERATION !!!! Now that is the holy grail of computing. Imagine if computers could generate code automatically !! Templates are one step towards this. it gives us a way to program programs that can create other programs. This gives ultimate power (ie if you are a geek).

Clever people have used and abused this technique for even more powerfull stuff, like how about passing a templated function or class itslef as parameter for another template ?

Drawbacks

Most people are put off by the syntax of the code and more importantly the synatx of the error messages that templates produce. The angle brackets that templates use can be nested to define a template of template of ….. etc.

If you remember that the compiler simply substitutes the template with the actual type and then compiles the code, it would then create error messages that look something like class A < class B , class c> :: line x error – some people hate this and i must admit, it becomes more difficult to parse once you start using the templates in a more powerful manner.

But that is no reason to ignore something as powerful as templates. IMO if you are not using templates, you are simply using C++ as a glorified C and nothing more.

So get cracking and write some cool logic, THAT WILL BE REUSED.

ps: Here is a real life example where i could use templates to create a generic solution to a very commonly occuring problem.

Advertisements