Skip to content

Chapter 20 of 31

Function Overloading and Templates

Resolve overloads and write constrained generic functions and classes.

42 minutes 10 quick checksBy Subha Prasad
Lesson 20 of 31Course navigation

Lesson content

Read, practise, then check your understanding

An overload set contains functions with the same name but different parameter lists. The compiler chooses the best viable function using conversion rankings. Return type alone cannot distinguish overloads, and excessive implicit conversions can create ambiguity.

void print(int value);
void print(double value);
void print(const char* value);

template <typename T>
T maximum(const T& left, const T& right) {
    return left < right ? right : left;
}

A function template is a recipe instantiated for concrete arguments. Class templates parameterize data structures and policies. Template definitions normally live in headers because the compiler must see them at the point of instantiation.

Concepts and specialization

#include <concepts>

template <std::totally_ordered T>
const T& smaller(const T& a, const T& b) {
    return b < a ? b : a;
}

Concepts express requirements and improve both APIs and diagnostics. Before C++20, SFINAE and type traits commonly constrained templates. Function templates can be explicitly specialized, but overloads are often clearer; class templates support partial specialization.

Perfect forwarding uses a forwarding reference T&& plus std::forward<T> to preserve the caller’s value category. Use it only in generic adapter code, because it enlarges overload sets and diagnostics. Prefer the smallest interface that satisfies real types, test templates with varied argument categories, and avoid assumptions not stated by constraints.

Knowledge check

Answer every question correctly to complete this chapter.

How does function overloading select a function?
Can functions overload on return type alone?
What does a function template describe?
What does a C++20 concept express?
Where are template definitions usually placed?
What is template argument deduction?
What is specialization?
What does if constexpr do?
What is a non-type template parameter?
Why can unconstrained template errors be difficult?

0 of 10 checks passed

Your progress is saved on this device.