Advertisement
Intermediate C++, Type Deduction & auto

How does template argument deduction work?

Short answer

When you call a template function, the compiler deduces the template parameters from the argument types, following rules similar to auto.

Save C++ mock interview
Advertisement
AModel answer
When you call a template function, the compiler deduces the template parameters from the argument types, following rules similar to auto. For a parameter T (by value), references and top-level const are stripped; for T& the reference is kept; for T&& (a forwarding reference) it deduces lvalue/rvalue-ness. Deduction lets you call templates without specifying types explicitly.
template <class T> void f(T x);
f(42);        // T = int
f("hi");      // T = const char*
Real-world example
A generic max() deduces its element type from the arguments, so callers don't specify it.
Likely follow-ups
  • How is T deduced for T& vs T? | What is a forwarding reference?
Related topics