navi homeaboutscreenshotsdownloaddevelopmentforum



A template is a class with an undefined type anywhere in it (for example a member variable, a function parameter or return value or even an undefined parent class). This undefined type gets replaced by a symbol. We'll usually use T as the symbol. Of course it's also possible to have more than one undefined type.

Possible applications for templates are: Generic lists that can store ints or strings or MyClasses or other lists, a container that stores an element of a specific class, a Factory, a stream and many more.

Because the exact specifications of templates aren't defined, the compiler can't just compile the template once. In fact the template gets compiled once in every source that uses the template. That's why it's not possible to just include the header file of a template. You always have to include the source too. This is why programmers usually write the whole code of the template into the header file.

Because templates are compiled several times, you should only put the minimum of functions and variables into the template itself and implement everything else in a base class. This has also another advantage: Because a template used with an int and the same template used with a string are two totally different classes, you can't assign them to a common variable. But with a comman base class, this is possible.


Definition and Implementation of the template:

// MyTemplate.h

class BaseTemplate
    // This function could also be implemented in
    void sayHello()
      { std::cout << "Hello!" << std::endl; }

    lots of functions and variables that don't use T

template <class T>
class MyTemplate : public BaseTemplate
    // This function must be implemented here, because it uses T
    T add(T var1, T var2)
      { return var1 + var2; }

Usage of the template:

#include "MyTemplate.h"

BaseTemplate* base;

MyTemplate<int>* template1 = new MyTemplate<int>();
std::cout << "Sum: " << template1->add(2, 5) << std::endl;

base = template1;

MyTemplate<std::string>* template2 = new MyTemplate<std::string>();
std::cout << "Sum: " << template2->add("abc", "def") << std::endl;

base = template2;


Sum: 7
Sum: abcdef
Last modified 9 years ago Last modified on Feb 28, 2008, 12:43:16 AM