Chapter 33 of 48

Templates

Suppose you need a function that returns the larger of two values. In the Function Overloading chapter we would write one version for int, another for double, another for char, another for std::string... Every version has exactly the same body; only the type changes. That is boring, error-prone, and impossible to finish, because new types can always appear.

Templates let you write the code once, with the type left as a parameter, and the compiler generates the type-specific versions for you. This style is called generic programming, and it is the foundation of the entire Standard Template Library (STL) that we start in the next chapter. Every std::vector<int> you will ever write is a template in action.


What Is a Template?

A template is a blueprint from which the compiler generates functions or classes. The blueprint has template parameters (usually types); when you use it with concrete arguments, the compiler creates a real function or class for those arguments. This generation step is called template instantiation.

C++ has several kinds of templates: function templates, class templates, variable templates (C++14), alias templates (C++11) and concepts (C++20). The first two are the ones you will use every day, so we focus on them.


Function Templates

#include <iostream>
#include <string>

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

int main() {
    std::cout << maxOf(3, 7) << '\n';                 // T = int
    std::cout << maxOf(2.5, 1.5) << '\n';             // T = double
    std::cout << maxOf('a', 'z') << '\n';             // T = char

    std::string s1 = "apple", s2 = "mango";
    std::cout << maxOf(s1, s2) << '\n';               // T = std::string

    std::cout << maxOf<double>(3, 4.5) << '\n';       // T given explicitly
}

Output:

7
2.5
z
mango
4.5

Let us break down the syntax:

  • template <typename T> introduces a template with one type parameter named T. The name is your choice; T is just the convention.

  • Inside the function, T is used like any real type.

  • You may write template <class T> instead. For declaring type parameters, class and typename mean exactly the same thing (a common interview question). typename is clearer because T can be int, which is not a class.

What the compiler actually does

A template by itself produces no machine code. Only when you call maxOf(3, 7) does the compiler deduce T = int from the arguments and instantiate a real function:

  template <typename T>            maxOf(3, 7)       →  int    maxOf(int a, int b)
  T maxOf(T a, T b)       ──────▶  maxOf(2.5, 1.5)   →  double maxOf(double a, double b)
  { return (a>b)?a:b; }            maxOf('a', 'z')   →  char   maxOf(char a, char b)
       (blueprint)                 maxOf(s1, s2)     →  std::string maxOf(std::string a, std::string b)

Each instantiation is a separate function, compiled and type-checked as if you had written it by hand. This all happens at compile time, so templates have no run-time cost compared with hand-written code. The price is longer compile times and potentially larger executables (code bloat) when many instantiations are created.

You can prove that instantiations are separate with a static local variable:

#include <iostream>

template <typename T>
void counter() {
    static int calls = 0;      // one separate variable per instantiation
    ++calls;
    std::cout << "calls = " << calls << '\n';
}

int main() {
    counter<int>();
    counter<int>();
    counter<double>();         // a different function: its own 'calls'
    counter<int>();
}

Output:

calls = 1
calls = 2
calls = 1
calls = 3

counter<int> and counter<double> each have their own calls.

Template argument deduction

Deduction must find one consistent type for each parameter. This fails:

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

int main() {
    maxOf(3, 4.5);   // int and double: what is T?
}
t2.cpp:7:10: error: no matching function for call to ‘maxOf(int, double)’
t2.cpp:7:10: note:   deduced conflicting types for parameter ‘T’ (‘int’ and ‘double’)

From the first argument T would be int, from the second double. Deduction does not perform the usual int-to-double conversion to make them agree. Fixes:

  • Give the argument explicitly: maxOf<double>(3, 4.5). Now no deduction happens and 3 is converted normally (that is the last line of the first program).

  • Convert yourself: maxOf(3.0, 4.5).

  • Use two type parameters, template <typename T, typename U> — but then you must decide what the return type is, which is more advanced.

A template works only if the type supports the operations

The body of maxOf uses >. If you call it with a type that has no >, the error appears at instantiation:

#include <iostream>

struct Point {
    int x, y;
};

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

int main() {
    Point p{1, 2}, q{3, 4};
    maxOf(p, q);     // Point has no operator>
}
t10.cpp: In instantiation of ‘T maxOf(T, T) [with T = Point]’:
t10.cpp:14:10:   required from here
t10.cpp:9:15: error: no match for ‘operator>’ (operand types are ‘Point’ and ‘Point’)

The template places implicit requirements on T. Either overload operator> for Point (see Operator Overloading) or don't use maxOf with it. In large templates these errors can be pages long; C++20 concepts, shown later in this chapter, make the requirements explicit and the errors short.

A related trap: maxOf("apple", "mango") compiles, but T is deduced as const char*, so it compares two addresses, not the text. The result is meaningless. Use std::string, or write a specialization (below).


Class Templates

A class can be a template too. This is how containers like std::vector<T> are written: the logic of storing and managing elements is the same whatever the element type is.

#include <iostream>
#include <string>
#include <stdexcept>

template <typename T, int Capacity>
class Stack {
    T items[Capacity];
    int count = 0;
public:
    void push(const T& value) {
        if (count == Capacity)
            throw std::overflow_error("stack is full");
        items[count++] = value;
    }
    T pop() {
        if (count == 0)
            throw std::underflow_error("stack is empty");
        return items[--count];
    }
    bool empty() const { return count == 0; }
    int size() const { return count; }
    int capacity() const { return Capacity; }
};

int main() {
    Stack<int, 5> numbers;
    numbers.push(10);
    numbers.push(20);
    numbers.push(30);
    std::cout << "size " << numbers.size() << " of " << numbers.capacity() << '\n';
    while (!numbers.empty())
        std::cout << numbers.pop() << ' ';
    std::cout << '\n';

    Stack<std::string, 2> words;
    words.push("hello");
    words.push("world");
    try {
        words.push("overflow!");
    }
    catch (const std::overflow_error& e) {
        std::cout << "Error: " << e.what() << '\n';
    }
    std::cout << words.pop() << ' ' << words.pop() << '\n';
}

Output:

size 3 of 5
30 20 10 
Error: stack is full
world hello

Points to notice:

  • Stack<int, 5> and Stack<std::string, 2> are two completely different classes. You cannot assign one to the other.

  • Stack on its own is not a type; it is a template. You must give its arguments (or let C++17 deduce them, see below).

  • A member function of a class template is only instantiated if it is actually used. So a class template can be used with a type that does not support every operation, as long as you never call the members that need it.

Non-type template parameters

int Capacity is a non-type template parameter: a compile-time value instead of a type. Its argument must be a constant expression, like 5 or a constexpr variable — never a value read at run time. Integers, enums, pointers and references are allowed; since C++20 floating-point values and simple "literal" class types are also allowed. The standard std::array<int, 10> uses this idea.

Defining member functions outside the class

Outside the class body, each member function must repeat the template header and the full class name with its parameters:

template <typename T, int Capacity>
class Stack {
    // ...
public:
    void push(const T& value);       // declaration only
};

template <typename T, int Capacity>
void Stack<T, Capacity>::push(const T& value) {
    // body
}

Default template arguments

Template parameters can have defaults, just like function parameters (see Default Arguments & Inline Functions): template <typename T = int, int Capacity = 100>. Then Stack<> means Stack<int, 100>. The standard containers use this heavily: std::vector<T> is really std::vector<T, std::allocator<T>>.

Class Template Argument Deduction (C++17)

Before C++17 you always had to write the template arguments of a class. Since C++17 the compiler can deduce them from the constructor arguments. This is called CTAD.

#include <iostream>
#include <string>

template <typename K, typename V>
class Pair {
public:
    K first;
    V second;
    Pair(K f, V s) : first(f), second(s) {}
    void print() const { std::cout << '(' << first << ", " << second << ")\n"; }
};

int main() {
    Pair<std::string, int> p1("Asha", 92);   // arguments written explicitly
    p1.print();

    Pair p2(3.5, 'x');                       // C++17 CTAD: Pair<double, char>
    p2.print();

    Pair p3(std::string("GATE"), 2027);      // Pair<std::string, int>
    p3.print();
}

Output:

(Asha, 92)
(3.5, x)
(GATE, 2027)

That is why, in modern code, you can write std::vector v = {1, 2, 3}; and get a std::vector<int>.


Template Specialization

Sometimes the general blueprint is wrong or inefficient for one particular type. A specialization provides a custom version for that type, while all other types still use the general (primary) template.

#include <iostream>
#include <cstring>

// Primary template
template <typename T>
bool isEqual(T a, T b) {
    return a == b;
}

// Full (explicit) specialization for const char*
template <>
bool isEqual<const char*>(const char* a, const char* b) {
    return std::strcmp(a, b) == 0;
}

// Primary class template
template <typename T>
class TypeInfo {
public:
    static const char* name() { return "some type"; }
};

// Full specialization for bool
template <>
class TypeInfo<bool> {
public:
    static const char* name() { return "bool"; }
};

// Partial specialization for ANY pointer type T*
template <typename T>
class TypeInfo<T*> {
public:
    static const char* name() { return "a pointer"; }
};

int main() {
    char buf1[] = "hello";
    char buf2[] = "hello";
    const char* x = buf1;
    const char* y = buf2;

    std::cout << std::boolalpha;
    std::cout << isEqual(10, 10) << '\n';        // primary, T = int
    std::cout << isEqual(x, y) << '\n';          // specialization: compares text

    std::cout << TypeInfo<int>::name() << '\n';
    std::cout << TypeInfo<bool>::name() << '\n';
    std::cout << TypeInfo<double*>::name() << '\n';
}

Output:

true
true
some type
bool
a pointer
  • Full (explicit) specialization — template <> followed by the exact type. isEqual<const char*> compares characters with strcmp instead of comparing pointers. (The two buffers hold the same text at different addresses; the primary template would have printed false.)

  • Partial specialization — still has template parameters, but restricts their form. TypeInfo<T*> matches every pointer type. Partial specialization is allowed only for class (and variable) templates, not for function templates; for functions you write an overload instead.

The standard library uses specialization too: std::vector<bool> is a special space-saving version that stores bits — we will see its quirks in the vector chapter.


Variadic Templates (C++11) and Fold Expressions (C++17)

A parameter pack, written typename... Args, lets a template accept any number of arguments of any types.

#include <iostream>
#include <string>

// Recursive variadic template (C++11 style)
void printAll() {                       // base case: no arguments left
    std::cout << '\n';
}

template <typename First, typename... Rest>
void printAll(const First& first, const Rest&... rest) {
    std::cout << first << ' ';
    printAll(rest...);                  // recurse with one fewer argument
}

// Fold expression (C++17)
template <typename... Args>
auto sum(Args... args) {
    return (args + ...);                // expands to a1 + (a2 + (a3 + ...))
}

template <typename... Args>
int countArgs(const Args&...) {
    return sizeof...(Args);             // number of arguments in the pack
}

int main() {
    printAll(1, 2.5, 'c', std::string("four"), "five");
    std::cout << sum(1, 2, 3, 4, 5) << '\n';
    std::cout << sum(1.5, 2.5) << '\n';
    std::cout << countArgs(1, "two", 3.0) << '\n';
}

Output:

1 2.5 c four five 
15
4
3
  • printAll peels off the first argument, prints it, and calls itself with the rest. The non-template printAll() with no parameters ends the recursion. This was the standard technique in C++11/14.

  • sum uses a C++17 fold expression: (args + ...) expands the pack with + between the elements, with no recursion needed.

  • sizeof...(Args) gives the number of elements in a pack at compile time.

Functions such as std::make_unique and vector::emplace_back are variadic templates that forward any number of constructor arguments.


Concepts (C++20)

We saw that a template places hidden requirements on its types, and that violating them produces errors deep inside the template. A concept is a named, compile-time predicate on types that states those requirements up front.

#include <iostream>
#include <concepts>

// 1. Constrained template parameter
template <std::integral T>
T gcd(T a, T b) {
    while (b != 0) {
        T r = a % b;
        a = b;
        b = r;
    }
    return a;
}

// 2. Our own concept
template <typename T>
concept Numeric = std::integral<T> || std::floating_point<T>;

// 3. requires-clause
template <typename T>
    requires Numeric<T>
T square(T x) {
    return x * x;
}

// 4. Abbreviated function template: 'auto' parameter (C++20)
void show(const auto& value) {
    std::cout << "[" << value << "]\n";
}

int main() {
    std::cout << gcd(48, 18) << '\n';
    std::cout << gcd(100L, 75L) << '\n';
    std::cout << square(7) << ' ' << square(1.5) << '\n';
    show(42);
    show("text");
}

Output:

6
25
49 2.25
[42]
[text]

Four new syntax forms appear here:

  1. template <std::integral T> — T must satisfy the standard concept std::integral (from <concepts>).

  2. concept Numeric = ...; — defines your own concept from existing ones.

  3. requires Numeric<T> — a requires-clause, another way to attach the constraint.

  4. void show(const auto& value) — an abbreviated function template: each auto parameter is an invisible template parameter.

Now a wrong call is rejected at the call site, with the reason:

#include <concepts>

template <std::integral T>
T gcd(T a, T b) {
    while (b != 0) {
        T r = a % b;
        a = b;
        b = r;
    }
    return a;
}

int main() {
    gcd(4.5, 1.5);   // double is not integral
}
t8.cpp:14:8: error: no matching function for call to ‘gcd(double, double)’
t8.cpp:4:3: note: constraints not satisfied
note: the expression ‘is_integral_v<_Tp> [with _Tp = double]’ evaluated to ‘false’

Some useful standard concepts: std::integral, std::floating_point, std::same_as<T, U>, std::convertible_to<T, U>, std::totally_ordered<T>, std::copyable<T>.


Why Templates Live in Header Files

With normal functions, you put the declaration in a .h file and the definition in a .cpp file. If you do that with a template, you usually get a linker error such as undefined reference to `int maxOf<int>(int, int)'. Why?

  • The compiler handles each .cpp file separately.

  • When compiling main.cpp, it sees maxOf(3, 7) and needs to instantiate maxOf<int> — but it only has the declaration, not the body. So it assumes the instantiation exists elsewhere.

  • When compiling maxof.cpp, it has the body but nobody there uses maxOf<int>, so no instantiation is generated.

  • The linker finds no maxOf<int> anywhere.

The usual solution: put the entire template definition in the header. This does not violate the one-definition rule, because templates (like inline functions) may be defined in several translation units as long as the definitions are identical. (The alternative, explicit instantiation such as template int maxOf<int>(int, int); in the .cpp file, only works for a known, fixed list of types.)


A Note on Dependent Names

Inside a template, if you refer to a type that is nested inside a template parameter, you must prefix it with typename:

#include <iostream>

template <typename Container>
void printFirst(const Container& c) {
    typename Container::value_type first = *c.begin();   // 'typename' required
    std::cout << first << '\n';
}

Until Container is known, the compiler cannot tell whether Container::value_type is a type or, say, a static variable. typename tells it "this is a type". (C++20 relaxed the rule in a few places where only a type can appear, but writing it is always correct. In practice, auto first = *c.begin(); avoids the issue.)


Templates Compared

Feature

Macros (#define)

Function overloading

Templates

Type checked?

No (text substitution)

Yes

Yes

Write code once?

Yes

No, one version per type

Yes

Works with new types automatically?

Yes, unsafely

No

Yes

Can be debugged / respects scope?

No

Yes

Yes

Templates and virtual functions both give "one interface, many types", but at different times:

Templates

Virtual functions

Kind of polymorphism

Compile-time (static)

Run-time (dynamic)

Decided when

At compile time, per instantiation

At run time, via the vtable

Requires a common base class?

No

Yes

Can store mixed types in one container?

No

Yes, through base pointers

Cost

No call overhead; larger code, slower builds

Small indirect-call overhead


Common Mistakes

  • Putting template definitions in a .cpp file — linker errors. Keep them in headers.

  • Expecting conversions during deduction — maxOf(3, 4.5) fails; specify <double>.

  • Using string literals with generic comparisons — T becomes const char* and pointers are compared.

  • Thinking Stack<int, 5> and Stack<int, 6> are the same type — they are different classes.

  • Using a run-time value as a non-type argument — Stack<int, n> with a normal variable n is an error.

  • Trying to partially specialize a function template — not allowed; overload instead.

  • Forgetting typename before dependent nested types like T::value_type.


Interview / GATE-Style Questions

Q1. Is there any difference between template <class T> and template <typename T>?

No, for declaring a type parameter they are identical, and T can be any type including built-ins like int. typename has an additional use (marking dependent nested types) that class does not.

Q2. When is a template instantiated, and does an unused template generate code?

A template is instantiated at compile time when it is used with specific arguments (implicit instantiation) or when explicitly requested. An unused template, and unused member functions of a class template, generate no code.

Q3. What is the output?
template<typename T> void f(T) { static int c = 0; cout << ++c; }
f(1); f(2); f(1.0); f('a'); f(3);

12113. Each instantiation has its own static variable: f<int> prints 1, then 2; f<double> prints 1; f<char> prints 1; then f<int> again prints 3.

Q4. Difference between full and partial specialization?

Full specialization fixes all template arguments (template <> class X<bool>). Partial specialization fixes only some or restricts their pattern (template <typename T> class X<T*>). Only class and variable templates can be partially specialized.

Q5. Why are templates usually defined completely in header files?

Because instantiation needs the full definition in every translation unit that uses the template with new arguments. If the definition is in another .cpp file, no instantiation for those arguments is generated, causing undefined-reference linker errors.

Q6. Compare templates and virtual functions for polymorphism.

Templates give compile-time polymorphism: the right code is generated per type, no common base is needed, calls can be inlined, but each type creates new code and mixed-type containers are not possible. Virtual functions give run-time polymorphism through a common base class and vtable dispatch, allowing heterogeneous collections at a small per-call cost.


Summary

  • Templates are compile-time blueprints; the compiler instantiates a separate function or class for each set of template arguments.

  • template <typename T> and template <class T> are equivalent.

  • Function template arguments are usually deduced; deduction allows no conversions, but you can specify arguments explicitly.

  • Class templates (like Stack<T, N>) can have type and non-type parameters and default arguments; C++17 CTAD deduces them from constructors.

  • Specialization customizes a template for particular types; partial specialization is for class templates only.

  • Variadic templates (C++11) take any number of arguments; fold expressions (C++17) expand them concisely.

  • Concepts (C++20) state type requirements explicitly and give clear errors.

  • Keep template definitions in header files.