Skip to content
Tutorials Center
My learning

Topics

Lesson 86 of 171 ยท Templates and Generic Programming

Function Templates

Learn C++ function templates - template syntax, template argument deduction, explicit template arguments, abbreviated templates with auto (C++20), and why templates live in headers.

Suppose you need a function that returns the larger of two values. For int you write one version, then a nearly identical one for double, then another for std::string. The bodies are character-for-character the same; only the types differ. Function Overloading lets them share a name, but you still maintain three copies, and the fourth type someone needs will require a fifth.

A function template solves this. You write the function once with a placeholder type, and the compiler generates a real function for each type you actually use. This is the foundation of generic programming in C++, and the entire standard library is built on it: std::sort, std::max, std::find and std::vector are all templates. This lesson covers the syntax, how the compiler works out the template arguments for you (and when it can't), explicit template arguments, the C++20 shorthand with auto parameters, how templates interact with ordinary overloads, and why template code goes in headers.

Writing a function template

A function template starts with a template parameter list: template <typename T>. Inside the function, T stands for some type that will be chosen later.

C++ One template, many types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

When you call larger(3, 7), the compiler sees two int arguments, decides T is int, and instantiates the template: it generates a real function int larger(int, int) with T replaced by int, then compiles it like any other function. Each distinct T produces its own instantiation, and calls with the same T share it. The result is exactly as fast as if you'd written each overload by hand.

A few syntax notes:

  • typename and class mean the same thing in a template parameter list: template <class T> is common in older code and in the standard library's documentation. This course uses typename.
  • The name T is a convention, not a rule. Descriptive names like Number, Container or Key help when there are several parameters.
  • The template must be declared before it's called, like a normal function.

What T must support

The template body puts requirements on T. larger uses < and copies values, so T must have an operator< and be copyable. Those requirements are implicit, and they're only checked when the template is instantiated with a concrete type. If a type doesn't qualify, the error appears inside the template body:

C++
struct Point { int x, y; };
larger(Point{1, 2}, Point{3, 4});
// In instantiation of 'T larger(T, T) [with T = Point]':
// error: no match for 'operator<' (operand types are 'Point' and 'Point')

For a two-line template that's fine, but deep inside library code these errors become notoriously long. C++20 concepts let you state the requirements in the signature (template <std::totally_ordered T>), so the error says plainly "Point doesn't satisfy totally_ordered". They get their own lesson: Concepts and Constraints.

Template argument deduction

Working out T from the call's arguments is called template argument deduction. It's what makes templates feel like ordinary functions. The rules resemble those of auto (see Type Deduction with auto):

  • For a parameter by value (T a), top-level const and references are dropped. Passing a const std::string& deduces T = std::string, and arrays decay to pointers.
  • For a parameter by reference (const T& a or T& a), const is kept as part of the referred type where needed, and arrays don't decay.
  • Every argument that mentions T must deduce the same type. And no implicit conversions are considered during deduction.

That last rule surprises everyone the first time:

C++ Deduction conflicts and three ways to fix them

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

From 3 the compiler deduces T = int, from 4.5 it deduces T = double, and since they disagree, deduction fails. It doesn't try to convert 3 to double, because then which conversion should win? When you specify larger<double>, there's nothing left to deduce, so ordinary conversions apply and 3 becomes 3.0.

std::common_type_t<A, B> (from <type_traits>) is the type that both convert to, the same type the conditional operator would produce: double for int and double, float for int and float.

Deduction with references and const

How you declare the parameter changes what's deduced. This matters for efficiency (copying a large std::vector into a by-value parameter is expensive) and for whether the function can modify the argument:

C++ What T becomes for different parameter forms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The same rules you learned for ordinary functions in Parameters: by Value, by Reference and by const Reference apply: take const T& for read-only access to possibly large objects, T& to modify the caller's object, and T for small types or when you need your own copy anyway. A fourth form, T&& in a template (a forwarding reference), accepts everything and is used with std::forward; it's covered in Variadic Templates and Fold Expressions.

Explicit template arguments

Sometimes there's nothing to deduce T from, typically when T appears only in the return type. Then the caller must spell it out in angle brackets. You've used this already: static_cast<int>(x) looks just like it, and std::make_unique<Widget>(...) works this way.

C++ Template arguments the compiler can't deduce

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Explicit arguments fill template parameters from left to right, and anything not given is deduced. That's why convert_all puts To first: callers name only the target type. If the order were <From, To>, every call would have to specify both.

Abbreviated function templates (C++20)

C++20 adds a shorthand: a function whose parameters are declared with auto is a template, without writing template <...> at all. Each auto parameter becomes its own invented template parameter.

C++ auto parameters make templates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

Note the difference from the larger template: add(2, 0.5) works, because a and b have separate invented types. If you want two parameters to share one type, you need the full template <typename T> form. Writing std::integral auto constrains the parameter with a concept, giving a clear error for unsupported types.

Abbreviated templates are ideal for short helpers. They're the same feature as generic lambdas ([](const auto& x) { ... }, see Lambda Expressions), now available for ordinary functions. Use the explicit template <typename T> syntax when you need to name the type in the body, to require two parameters of the same type, or to let callers pass explicit template arguments.

Templates and overloading

Function templates can be overloaded with each other and with ordinary functions. When both a template and a non-template match equally well, the non-template wins. That lets you write a generic version plus special handling for particular types:

C++ Overloads next to a template

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with std::cin or std::getline), it gets the next line from this box.

The compiler collects every candidate, deduces template arguments for each template, and picks the best match: an exact non-template beats a template, and among templates the more specialized one (T* is more specific than const T&, because it accepts only pointers) wins. Writing equal<int> with explicit arguments excludes non-template functions entirely. For details on choosing between overloading and specializing a template, see Template Specialization.

Templates live in headers

There's one practical rule that trips up everyone splitting a project into files: put template definitions in headers, not in .cpp files.

The reason is how templates are compiled. A template isn't code yet; it's a recipe. The compiler can only instantiate larger<double> when it sees both the call and the full template body in the same translation unit. If larger is only declared in utils.h and defined in utils.cpp, then main.cpp compiles the call, assumes larger<double> exists somewhere, and the linker later fails because nobody ever instantiated it:

TEXT
undefined reference to `double larger<double>(double, double)'

So template libraries are usually header-only: the whole definition goes in the header (function templates are implicitly allowed in many translation units, like inline functions; see inline Functions). The alternative, used for large templates with a known set of types, is explicit instantiation: keep the body in the .cpp file and list the types there.

C++
// utils.h
template <typename T> T larger(T a, T b);       // declaration only

// utils.cpp
template <typename T> T larger(T a, T b) { return (a < b) ? b : a; }
template int larger<int>(int, int);             // explicit instantiations:
template double larger<double>(double, double); // only these types will link

C++20 modules change this picture, because a module interface can export templates without textual headers; see C++20 Modules. Learn more about splitting code in Header Files and Multiple Source Files.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Given template <typename T> T larger(T a, T b), what does larger(2, 7.5) do?

    Each argument deduces T independently and no conversions are tried during deduction. The conflict makes deduction fail; write larger<double>(2, 7.5) instead.
  2. 2. Which call compiles for template <typename T> T parse(const std::string& s)?

    T appears only in the return type, so it can't be deduced from the arguments. The caller has to give it explicitly.
  3. 3. What does auto add(auto a, auto b) { return a + b; } return for add(1, 2.5)?

    Each auto parameter is a separate template parameter, so a is int and b is double. int + double gives a double.
  4. 4. A non-template void show(int) and a template template <typename T> void show(T) both exist. Which runs for show(5)?

    When a template specialization and an ordinary function match equally well, overload resolution prefers the non-template function.
  5. 5. A function template is declared in math.h and defined only in math.cpp. main.cpp includes math.h and calls it with double. What typically happens?

    Instantiation needs the template body at the call site. main.cpp can't instantiate it and math.cpp never did, so the symbol is missing unless math.cpp explicitly instantiates it.

Summary

  • template <typename T> before a function makes a function template; the compiler instantiates a real function for each set of template arguments you use, at no run-time cost.
  • The body defines what T must support, and errors appear at instantiation. Concepts (C++20) state those requirements up front.
  • Deduction works out T from the arguments: by-value parameters drop const and references, all arguments must agree, and no conversions are tried.
  • Fix conflicts with explicit arguments (larger<double>(3, 4.5)), a cast, or separate type parameters with std::common_type_t.
  • Give template arguments explicitly when they can't be deduced (parse<int>(text)); they fill parameters left to right, so put the ones callers specify first.
  • C++20 abbreviated templates (void f(const auto& x)) create one template parameter per auto; std::integral auto adds a constraint.
  • Non-templates win ties against templates, and more specialized templates beat general ones.
  • Template definitions belong in headers (or need explicit instantiation), because the compiler needs the body where it's used.

Next: Class Templates, generic types like Stack<T>.