Main Content

Templates in C++ - defining a family pattern of methods / functions

Archive - Originally posted on "The Horse's Mouth" - 2011-08-12 23:03:02 - Graham Ellis

In C, function names need to be unique. If you try to compile or load two functions of the same name, even with a different number / type of parameters, you'll get an error rather than a runnable file out of your compile / load process. See [here].

In C++, you can have methods (functions) in each class (namespace) of the same name - and indeed this is the whole basis of polymorphism, where the piece of code to be run when the program's in operation is selected dynmaically based on the type of data on which it's run. This can even change from one iteration of a loop to another, so that if you have an array that contains fishing rods and skis, you can call different "getlength" pieces of code on each of them without having to use any if or switch type constructs. And in C++, you can also gave multiple methods / functions of the same name, each with a different number / type of parameters, and the compiler, loader and runtime library will sort them out for you, calling the right one an the right time. Example [here], with minimal changes from the C example above.

If you require a whole family of functions in C++, you may use a function template. There's an example [here] on our web site.

Templates are essentially patterns - you can say that there is a whole pattern of methods which is available if you call a function of a certain name, with differing data types in use. The example that I've linked to above defines a function called "exchange" which swaps over two variables ... and needs a third variable internally of the same type to act as a temporary store.

Sample template definition:

  template<typename T>
    void exchange(T& x, T& y)
    {
      T tmp = x;
      x = y;
      y = tmp;
    }


Templates can have several differing types in their call, and you can even define multiple templates of the same name, with a generic one initially then exception(s) where a particular type is passed in as a parameter. In an extended examle [here], we have modified our "exchange" template to give it functionally different behaviour via an alternative template if it's called with bool parameters.

Also in that example, we've used a template to give a variable return type too, and to force the incoming parameters to be specified / cast too:

  double gloucester = differ<float, long int, double>(boat,length);

Looking at that notation, you'll spot that standard library code is in fact template based too, with the C++ vector, for example, using a template to allow the vector to hold data of a type of your choosing.