liveBook · Manning

Function template

As explained in Learn C++ by Example

A function template is a parameterized function definition from which functions for specific template arguments can be generated.

A function template is a parameterized function definition that generates functions for particular argument types. It replaces repetitive overloads when one operation should work across several type combinations. section 1.4.2

Generic addition

A two-type addition function can deduce its return type from the expression it performs: template<typename T, typename U> auto simple_plus(T lhs, U rhs) -> decltype(lhs + rhs). Unlike std::plus<int>, which converts 1.23 to int, std::plus<> preserves the differing argument types and produces 2.23 for 1 and 1.23. section 1.4.2

Listing 1.3 A function to add two different types
template<typename T, typename U>
auto simple_plus(T lhs, U rhs) -> decltype(lhs + rhs)
{
   return lhs + rhs;
}

Inspect a complete two-parameter function template using decltype to express the result of lhs + rhs. section 1.4.2

Templates also make behavior injectable. The answer-smash game accepts a selector template parameter, allowing production code to sample a dictionary while tests choose the first or last matching item deterministically. section 7.3.3

Listing 7.11 Selecting a word from a multimap
template <typename T>
std::tuple<std::string, std::string, int>
    select_overlapping_word_from_dictionary(std::string word,
        const std::multimap<std::string, std::string>& dictionary,
        T select_function)
{
    size_t offset = 1;
    while (offset < word.size())
    {
        auto stem = word.substr(offset);
        auto lb = dictionary.lower_bound(stem);                      #1
        auto beyond_stem = stem;                                     #1
        beyond_stem += ('z' + 1);                                    #1
        auto ub = dictionary.upper_bound(beyond_stem);               #1
        if (lb != dictionary.end() &&                                #2
            lb != ub)                                                #2
        {
            std::vector<std::pair<std::string, std::string>> dest;   #3
            select_function(lb, ub, std::back_inserter(dest));       #3
            auto found = dest[0].first;                              #3
            auto definition = dest[0].second;                        #3
            return { found, definition, offset };    
        }
        ++offset;                                                    #4
    }
    return {"", "",  - 1};                                           #5
}

Follow a function template that searches a multimap and delegates selection to a supplied callable. section 7.3.3

How Learn C++ by Example covers it

How deep it goes
Explains syntax, return-type deduction, library alternatives, and testing use; stops short of extensive template internals.
Examples
Uses generic addition, std::plus<int>, std::plus<>, and a dictionary selector tested with deterministic lambdas.
What it assumes
Assumes basic C++ functions and operators while introducing template parameters, decltype, lambdas, and callable injection through examples.
What you can do after
Build reusable type-generic functions and test configurable behavior by supplying alternative callable selectors.
How it connects
Connects function templates with function overloading, type deduction, trailing return types, lambda expressions, std::plus, multimaps, and tuples.

Also explained in

Compare how 2 books explain function template →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn C++ by Example. The section links point to the parts of the book it draws on.