Learn C++ Β· 11/15

Templates: Writing Generic Code

6 min read

πŸ‘‹ Welcome to the "Don't Repeat Yourself" Dojo

Welcome back, C++ padawan! πŸ₯‹ Today, we are tackling one of the most powerful (and admittedly, sometimes scary) features of C++: Templates.

If you have ever found yourself writing the same function three times just to handle int, float, and double, you have officially entered the "Boilerplate Zone." It’s boring, it’s prone to errors, and frankly, we have better things to doβ€”like arguing about tabs vs. spaces.

Templates allow you to write code that works with any data type. It is the blueprint, not the building. Let's dive in! πŸš€


1. Function Templates: Type-Independent Algorithms

πŸ›‘ The Problem

Imagine you need a function to find the maximum of two numbers.

Without Templates:

cpp
int getMax(int a, int b) {
    return (a > b) ? a : b;
}

double getMax(double a, double b) {
    return (a > b) ? a : b; // πŸ™„ heavily breathing
}

char getMax(char a, char b) {
    return (a > b) ? a : b; // 😭 make it stop
}

If you want to support 10 types, you write 10 functions. If you find a bug in the logic, you fix it in 10 places. This is maintenance hell.

πŸ’‘ The Solution: Function Templates

A Function Template is a blueprint. You tell the compiler: "I don't care what the data type is. Just call it T, and generate the correct version when I actually use it."

πŸ’» The Syntax

We use the keyword template followed by template parameters inside < >.

cpp
#include <iostream>

// The Blueprint
template <typename T>
T getMax(T a, T b) {
    return (a > b) ? a : b;
}

int main() {
    // Usage
    std::cout << getMax(5, 10) << std::endl;      // Compiler creates getMax(int, int)
    std::cout << getMax(3.5, 9.1) << std::endl;   // Compiler creates getMax(double, double)
    std::cout << getMax('a', 'z') << std::endl;   // Compiler creates getMax(char, char)
    
    return 0;
}

🧠 How it Works (Under the Hood)

Templates are not compiled into code directly. They are instantiated at compile time.

  1. When you call getMax(5, 10), the compiler sees you passed integers.
  2. It looks at the template.
  3. It silently generates a specific function where T is replaced by int.
  4. This looks exactly like the manual version you would have written, but the compiler did the typing for you. Thanks, compiler! πŸ€–

Note: typename T and class T are interchangeable in this context. You will see both in the wild. typename is generally preferred in modern C++ for clarity because T can be int (which isn't a class).


2. Class Templates: Generic Data Structures

πŸ›‘ The Problem

You want to build a "Box" class that holds an item.

  • Monday: You need a IntBox to hold an integer.
  • Tuesday: You need a StringBox to hold a text.
  • Wednesday: You realize you need a ZombieBox for your game entity.

Creating a new class for every data type violates the DRY (Don't Repeat Yourself) principle.

πŸ’‘ The Solution: Class Templates

Just like function templates, we can make the entire class generic.

πŸ’» The Syntax

cpp
#include <iostream>

// Class Template Definition
template <typename T>
class Box {
private:
    T item;

public:
    Box(T i) : item(i) {}

    T getItem() {
        return item;
    }
    
    void setItem(T i) {
        item = i;
    }
};

int main() {
    // Usage: We MUST specify the type inside < >
    Box<int> intBox(123);
    Box<std::string> strBox("Hello World");

    std::cout << intBox.getItem() << std::endl;
    std::cout << strBox.getItem() << std::endl;

    return 0;
}

πŸ€“ Industry Insight

You have likely already used this without knowing! The Standard Template Library (STL) is built entirely on this.

  • std::vector<int> is just a class template named vector instantiated with int.
  • std::vector<std::string> is the same template instantiated with string.

3. Template Instantiation and Parameters

Template Parameters (More than just Types)

You aren't limited to just typename T. You can also pass values (Non-Type Template Parameters), usually integers. This is how std::array works.

Example: A Fixed-Size Array Wrapper

cpp
template <typename T, int Size>
class StaticArray {
private:
    T data[Size]; // Size is known at compile time!
public:
    int getSize() const { return Size; }
};

int main() {
    StaticArray<int, 5> myArr; // Creates an array of 5 ints
    // StaticArray<int, 10> myArr2; // This is a DIFFERENT type to the compiler!
}

Implicit vs. Explicit Instantiation

  • Implicit: The compiler guesses the type based on arguments (mostly for functions).
    • getMax(5, 6) -> T is int.
  • Explicit: You tell the compiler exactly what T is.
    • getMax<double>(5, 6) -> Forces T to be double, even though 5 and 6 are ints.

⚠️ The "Linker Error" Nightmare (CRITICAL)

This is the #1 issue beginners face.
Rule: Template definitions usually need to go in the Header File (.h), not the Source File (.cpp).

Why?
If you put the template logic in a .cpp file, the compiler compiles that file separately. When it compiles your main.cpp, it doesn't know how to generate the code for Box<int> because the blueprint is hidden inside another .cpp file that hasn't been linked yet.

Best Practice:
Put your template declaration and implementation in the header file. Sometimes these are saved as .hpp or .tpp to distinguish them, but .h works fine.


4. Practical Use Cases for Templates

In the real world, you won't always write your own templates, but you will consume them daily.

A. The Standard Template Library (STL)

This is the bread and butter of C++.

  • Containers: std::vector<T>, std::list<T>, std::map<K, V>.
  • Smart Pointers: std::unique_ptr<T>, std::shared_ptr<T>.

B. Generic Algorithms

Writing a sorting algorithm for integers, then another for floats, then another for custom objects is a waste of time.
std::sort is a template function that works on anything that can be compared.

cpp
#include <vector>
#include <algorithm> // Contains the templates
#include <iostream>

int main() {
    std::vector<int> nums = {4, 2, 5, 1, 3};
    
    // std::sort is a function template!
    std::sort(nums.begin(), nums.end());

    for(int n : nums) std::cout << n << " ";
    return 0;
}

C. Type Traits & Metaprogramming (The Advanced Stuff)

In high-performance libraries (like game engines or financial systems), developers use templates to perform calculations at compile time to save CPU cycles at runtime. This involves "Type Traits" (checking if T is an integer, or a pointer, etc.).


πŸ§ͺ Quick Review

  1. Templates let you write code once for multiple data types.
  2. Function Templates automate algorithm generation (sort, max).
  3. Class Templates automate data structure generation (vector, Box).
  4. Template Definitions usually live in header files (.h).
  5. Use the STL; don't reinvent the generic wheel unless you are studying.

πŸ“š References & Further Reading

Happy Coding! 🐧

Challenge

You are tasked with implementing a generic, fixed-size array container using C++ templates.

1. Class Template: FixedArray

Create a class template named FixedArray that takes two template parameters:

  1. A type parameter T for the element type.
  2. A non-type parameter size_t N for the fixed size of the array.

The class must have the following public interface:

  • A size() method that returns the size N of the array. This method should be constexpr.
  • An at(size_t index) method that returns a T& reference to the element at the given index. This method must perform bounds checking and throw std::out_of_range if the index is out of bounds (i.e., index >= N).
  • An overloaded const version of at(size_t index) that returns a const T& reference. This should also perform bounds checking.

The underlying data should be stored in a private C-style array.

2. Function Template: fill

Create a non-member function template named fill that takes two arguments:

  1. A reference to a FixedArray<T, N> object.
  2. A constant reference to a value of type T.

This function should set every element in the given FixedArray to the provided value.

Expected result

Your final code should contain a complete and correct implementation for both the FixedArray class template and the fill function template.

A correct implementation will satisfy the following criteria:

  1. FixedArray Class Template:

    • The template declaration is template <typename T, size_t N>.
    • It contains a private member T m_data[N];.
    • The size() method is public, constexpr, and returns N.
    • The at(size_t index) method returns a T&, checks if index >= N, throws std::out_of_range on failure, and returns m_data[index] on success.
    • The const at(size_t index) method returns a const T& and has the same bounds-checking logic.
  2. fill Function Template:

    • The template declaration is template <typename T, size_t N>.
    • The function signature is void fill(FixedArray<T, N>& arr, const T& value).
    • The implementation uses a loop (e.g., a for loop from 0 to arr.size()) to assign value to each element of the array, for instance by using the at() method.
cpp

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.