Next Previous Contents

16. Templates

Templates is a feature in C++ which enables generic programming, with templates code-reuse becomes much easier.

Consider this simple example:

#include <string>
#include <iostream>

void printstring(const std::string& str) {
    std::cout << str << std::endl;

int main()
    std::string str("Hello World");

Our printstring() takes a std::string as its first argument, therefore it can only print strings. Therefore, to print a character array, we would either overload the function or create a function with a new name.

This is bad, since the implementation of the function is now duplicated, maintainability becomes harder.

With templates, we can make this code re-usable, consider this function:

template<typename T> 
void print(const T& var) {
    std::cout << var << std::endl;

The compiler will automatically generate the code for whatever type we pass to the print function. This is the major advantage of templates. Java doesn't have templates but Java uses inheritance to achieve generic programming. For example in Java:

public static void printstring( Object o ) {
  System.out.println( o );
You can pass in any object you want.


Next Previous Contents