Functions, overloading and templates

One name, many types — first by writing each version by hand, then by letting the compiler write them.

What you'll learn
  • Write functions that return values and functions that return nothing
  • Explain how overloading and templates differ, and when each is resolved
  • Use namespaces to keep two functions with the same name apart

08functions.cpp defines two functions over std::array<int, 3>: one that prints (returning void) and one that sums (returning int):

int sum(std::array<int, 3> array) {
    int sum = 0;
    for (int value : array) sum += value;
    return sum;
}

sum(my_array_1) on {1, 2, 3} returns 6. The array is passed by value — the function gets its own copy. For three ints that is free; lesson 5 shows when it is not.

Overloading

To print a std::array<float, 3> as well, 08function_overloading.cpp writes a second function with the same name and a different parameter type. The compiler picks the matching one at each call site. It works, but the two bodies are identical — a sign that the compiler should be writing them.

Templates

A template is a recipe the compiler instantiates once per type it is used with:

template<typename T>
void print_array1(T array) { for (auto value : array) std::cout << value << ' '; }

void print_array(auto array) { ... }     // C++20 shorthand for the same thing

print_array(my_float_array) deduces the type itself; writing print_array<std::array<int, 3>>(my_int_array) names it explicitly. Both lines print 1 2 3 and 1.1 2.2 3.3. (print_array1 is defined but never called, so it is never instantiated — templates that are not used produce no code at all.)

The shorthand auto parameter needs C++20, which is why the readme compiles with --std=c++20.

Template specialisation

08template_specialization.cpp overrides the recipe for one type:

template<>
void print_array(std::array<int, 3> array) {
    std::cout << "This is template specialization!";
}

Now the int call takes the special path. One detail shows in the output: the specialised version prints no newline, so the next line runs straight on — This is template specialization!1.1 2.2 3.3.

Namespaces

36namespaces.cpp defines two functions both called print, one inside namespace A. print() calls the global one and A::print() the other. The std:: in front of cout is the same idea: the standard library lives in namespace std so that its names never collide with yours.

Try it yourself. Call print_array from 08functions.cpp with a std::array<int, 4>. Read the error, then fix it twice: once with a template, and once with a std::span<const int> parameter (lesson 3).

View source on GitHub →