Whole document tree

Whole document tree

C++ Programming HOW-TO: Templates 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, therefor it can only print strings. Therefor, 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-useable, 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, and therefor generic programming and code reuse is harder in Java.


Next Previous Contents