← SEARCHABLE ARCHIVE
C / C++ · 2026-07-22

C++ from Basics to Mastery — Part 13

Reduce duplicate code of different types with templates

INTERACTIVE READING MODE →

The articles written on this blog were created with the goal of teaching. Also, the information in the article may be incorrect, so please be careful.

There are times when the function for finding an item ID and the function for finding a monster ID have almost the same shape. If only the data type is different and the behavior is the same, you can create common rules using templates rather than copying code.

function template

Let's start by creating a function that returns the larger of the two values.

template <typename T>
T Max(const T& a, const T& b)
{
    return a < b ? b : a;
}

int highLevel = Max(10, 20);
float highDamage = Max(12.5f, 8.0f);

Tis a place that changes to the actual type when calling a function. The compilerMax<int>andMax<float>Create each function as needed.

butMax(10, 3.5f)If different types are passed, compilation fails because one T cannot be determined. You must explicitly match the types or design templates that accept both types separately.

class template

If you want to use the same size slot for multiple types, you can also create a class as a template.

template <typename T, std::size_t Size>
class Inventory
{
public:
    T& At(std::size_t index)
    {
        return slots.at(index);
    }

    const T& At(std::size_t index) const
    {
        return slots.at(index);
    }

private:
    std::array<T, Size> slots{};
};

Inventory<Item, 20> itemInventory;
Inventory<Skill, 8> skillInventory;

T is the type and Size is a value determined at compile time. std::arraySince the size does not change at runtime, it is good for expressing a fixed slot.

Templates and header files

A regular function can have its declaration in the header and its definition in cpp. However, the definition of a template must be visible at the time the compiler creates code for the actual type.

// Inventory.h
template <typename T>
class Inventory
{
public:
    void Add(const T& value)
    {
        values.push_back(value);
    }

private:
    std::vector<T> values;
};

So template definitions are usually written in the header. If you put only the declaration in the header and hide the definition in cpp, a link error may occur because a specific type of code cannot be found.

Criteria for using templates

If the code is of a different type but has the same meaning, a template reduces duplication. Conversely, if code with different actions and responsibilities is forced into a single template, conditional statements and special processing increase.

Templates are not a function that generalizes all code. It is better to think of it as a tool that safely applies the same rules to multiple types and prevents incorrect combinations at the compilation stage.