Skip to content

One Useful Function Template

The Course
•
35 min study

The tracker's summary prints two totals: minutes still pending and minutes completed. Written out by hand, they are two loops that are identical except for one condition, task.state() == State::todo in one and State::done in the other. Duplicated loops drift apart: someone fixes a bug in one and forgets the other. You would like one loop that takes "which tasks count" as an argument.

A lambda can express the condition, but what is the parameter's type? Every lambda has its own unique type, with no name you can write. A function template solves that. template<class Predicate> says "this function works for any type Predicate"; when you call it with a lambda, the compiler deduces Predicate from the argument and generates a version of the function for that exact type. You write the traversal once, and the compiler writes as many copies as you use.

This is the one template the project needs. Day 6 does not go further into template techniques; it is about using a small template well and testing it properly.

Predict and run

sum_if adds the values the predicate selects. What is the total?

Predict before running C++
#include <iostream>
#include <vector>

template<class Predicate>
long sum_if(const std::vector<int>& values, Predicate matches) {
    long total = 0;
    for (int value : values) { if (matches(value)) { total += value; } }
    return total;
}

int main() {
    std::vector<int> values{10,25,40};
    std::cout << sum_if(values,[](int value) { return value >= 25; }) << "\n";
    return 0;
}
Check your prediction
Text
65

25 and 40 match, so the total is 65. The template never mentions lambdas: it only requires that matches(value) is a valid call whose result can be tested in an if. Anything that satisfies that, a lambda, a function or a function pointer, works. The total is a long because the tracker's worst case, 1000 tasks of 180 minutes, is 180,000, and long is guaranteed to hold at least 2,147,483,647 while int is only guaranteed to reach 32,767.

One template, many instantiations

Each distinct argument type produces a separate instantiation, a real function the compiler generates and type-checks. The two calls below use two different lambda types, so the program contains two versions of sum_if, each as efficient as a hand-written loop with the condition inlined.

Two reports, one traversal C++
#include <iostream>
#include <vector>

struct Task { int minutes; bool done; };

template<class Predicate>
long total_minutes_if(const std::vector<Task>& tasks, Predicate matches) {
    long total = 0;
    for (const Task& task : tasks) {
        if (matches(task)) { total += task.minutes; }
    }
    return total;
}

bool is_done(const Task& task) { return task.done; }

int main() {
    const std::vector<Task> tasks{{25, false}, {10, true}, {25, false}, {40, true}};
    std::cout << "Pending: " << total_minutes_if(tasks, [](const Task& t) { return !t.done; }) << "\n";
    std::cout << "Completed: " << total_minutes_if(tasks, is_done) << "\n";
    std::cout << "All: " << total_minutes_if(tasks, [](const Task&) { return true; }) << "\n";
    return 0;
}
Text
Pending: 50
Completed: 50
All: 100

The second call passes an ordinary function, so Predicate is deduced as a function pointer type. The third lambda leaves its parameter unnamed, which tells the compiler, and the reader, that it ignores the task.

Because the compiler generates each instantiation where the template is used, it needs the template's full definition there, not just a declaration. That is why the project defines total_minutes_if in tracker.h rather than in tracker.cpp: every file that includes the header can instantiate it.

When the argument does not fit

Type checking happens at instantiation, so a wrong argument produces an error inside the template body. Passing the number 25 where a predicate belongs:

Shell
main.cpp:7:36: error: called object type 'int' is not a function or function pointer
    7 |     for (int value : values) { if (matches(value)) { total += value; } }
      |                                    ^~~~~~~
main.cpp:13:29: note: in instantiation of function template specialization 'sum_if<int>' requested here

Read template errors from the "in instantiation" note backward to your own call. C++20 concepts let a template state its requirement up front. Writing template<std::predicate<int> Predicate> (from <concepts>) makes the same mistake fail at the call, with a note that std::predicate<int, int> was not satisfied. The project keeps the plain class Predicate and documents the contract in a comment; either style is reasonable for a single small template.

Practice

Exercise

Your turn

Write template<class T, class Predicate> std::vector<T> select(const std::vector<T>& values, Predicate matches) that returns a new vector of the matching elements, in order. Use it with std::vector<int>{1, 2, 3, 4} to select even numbers, with std::vector<std::string>{"Read", "Plan", "Review"} to select titles starting with R, and with an empty vector. Print:

Text
even: 2 4
starts with R: Read Review
empty: (none)
Your workspace C++
#include <iostream>
#include <string>
#include <vector>

// Write select here.

int main() {
    return 0;
}
Hint 1: the idea

The predicate chooses elements; the traversal copies them into the result. T is deduced from the vector, and Predicate from the lambda, so callers never write either type.

Hint 2: a first step

Write the integer case first as an ordinary function with the test written into it: std::vector<int> select_evens(const std::vector<int>& values), keeping each value where value % 2 == 0. Get even: 2 4 printing. Then make it a template: add template<class T, class Predicate>, change int to T, add a Predicate matches parameter, and replace the built-in test with matches(value). The call becomes select(numbers, [](int n) { return n % 2 == 0; }), and the string vector should now work too.

Show one solution
Run the solution C++
#include <iostream>
#include <string>
#include <vector>

template<class T, class Predicate>
std::vector<T> select(const std::vector<T>& values, Predicate matches) {
    std::vector<T> result;
    for (const T& value : values) {
        if (matches(value)) { result.push_back(value); }
    }
    return result;
}

template<class T>
void print(const char* label, const std::vector<T>& values) {
    std::cout << label << ":";
    if (values.empty()) { std::cout << " (none)"; }
    for (const T& value : values) { std::cout << ' ' << value; }
    std::cout << "\n";
}

int main() {
    const std::vector<int> numbers{1, 2, 3, 4};
    const std::vector<std::string> titles{"Read", "Plan", "Review"};
    print("even", select(numbers, [](int n) { return n % 2 == 0; }));
    print("starts with R", select(titles, [](const std::string& t) { return !t.empty() && t.front() == 'R'; }));
    print("empty", select(std::vector<int>{}, [](int) { return true; }));
    return 0;
}
Text
even: 2 4
starts with R: Read Review
empty: (none)

The same select was instantiated for int and for std::string, and print likewise, so neither depends on the element type. The title predicate checks !t.empty() before t.front(), because front() on an empty string is undefined behavior. The empty call shows the zero-match case needs no special code. The next lesson is about testing a template like this so that a broken version cannot pass.

Was this article helpful?

Your response is saved on this device.