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

