Lesson 19 — Generic Programming

Templates

Templates let you write a single function or class that works with any data type, with the compiler generating a specific version for each type you actually use.

Function Templates

Without templates, you would need a separate max function for integers, doubles, and every other type you wanted to compare. A function template writes the logic once, using a placeholder type name that the compiler fills in based on how the function is called.

C++ — Function template
template <typename T>
T getMax(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    std::cout << getMax(3, 7) << std::endl;         // works with int
    std::cout << getMax(2.5, 1.1) << std::endl;     // works with double
    std::cout << getMax(std::string("cat"), std::string("dog")) << std::endl; // and string
    return 0;
}

Class Templates

The same idea applies to entire classes. A class template can hold or process any type, and the standard library's std::vector<T> is itself a class template — T is replaced with whatever type you use it with.

template <typename T> class Box { private: T contents; public: void set(T value) { contents = value; } T get() { return contents; } }; Box<int> intBox; Box<std::string> stringBox;

Common Mistakes

  • Forgetting that a template function must actually be usable with the operations you write in its body — getMax requires > to be defined for type T.
  • Confusing generic templates with function overloading — templates generate code per type automatically rather than requiring you to write each version.
  • Placing template implementations in a .cpp file instead of a header, which typically causes linker errors since templates are compiled per use.
  • Overcomplicating simple code with templates when a normal function for one or two known types would be clearer.

Professional Tip

Templates are compiled only when used, and only for the exact types they're used with. This is why template-related compiler errors can look intimidating — the error often points into the template's internals rather than your calling code.

Your Turn

Write a template function called swapValues that takes two references of the same generic type and swaps their values. Test it with two ints and then with two strings.

Mini Quiz

What is the main benefit of using a template instead of writing separate functions for each type?