Learn C++
#include "templates/template_deduction.hpp"

Template Argument Deduction in C++

//concept

Deduction infers template arguments from call arguments so max2(3, 7) needs no <int>: by-value parameters drop references/const, T& preserves them, and arrays decay to pointers unless taken by reference (T(&)[N] keeps size!). Conflicts (f(1, 2.5) with one T) fail rather than guess.

C++17 CTAD extends deduction to class templates (pair p(1, 2.0); → pair<int,double>), and C++20 abbreviated function templates (auto parameters on plain functions) make every function potentially generic. Knowing the three deduction shapes (value, reference, universal) predicts nearly every outcome.

//how it works
1

Value drops qualifiers

template <typename T> f(T x) with an int argument gives T=int even for const int& inputs — copies erase decoration.

2

Reference preserves

template <typename T> f(T& x) keeps constness and identity — T deduces as const int for const inputs, enabling perfect views.

3

Arrays need reference form

By value, int[5] decays to int*; template <typename T, size_t N> f(T(&)[N]) preserves the bound — the only way to keep array size.

4

CTAD for classes

std::pair p(1, 2.5); deduces pair<int, double> from the constructor — guides fill gaps where deduction alone can't.

//example
#include <iostream>
#include <utility>
 
template <typename T>
void show(T x) { std::cout << x << std::endl; }
 
int main() {
show(42);
std::pair p(1, 2.5);
std::cout << p.first << ", " << p.second << std::endl;
return 0;
}
Output
42
1, 2.5
1show(42) deduces T=int by value — no angle brackets needed at the call.
2std::pair p(1, 2.5) uses CTAD to become pair<int, double> automatically.
3All three values print with their deduced types intact.
//use cases
Predicting deduced types when auto and templates interact
Preserving array bounds through reference-parameter templates
Writing forwarding functions with T&& that keep value categories
Leaning on CTAD to drop redundant pair<int, string> spellings

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C++ yourself — building beats watching.