1. Problem It Solves
Template deduction infers parameters from call arguments, then overload resolution ranks the viable ordinary and template candidates. It makes an important constraint visible instead of leaving readers to guess. This lesson keeps only the C++11 core that fits one focused day.
2. Prerequisites
The ideas from Day 29, plus basic variables, functions, and output already introduced.
3. Core Idea
Mental model: Template deduction infers parameters from call arguments, then overload resolution ranks the viable ordinary and template candidates. Identify the relevant value or state, who owns it, and whether the rule acts during compilation or execution.
4. Minimal Syntax
template<class T> void show(T); template<class T> void show(T*);5. How It Works
The example creates a tiny fixed state with no keyboard input.
C++11 or the standard-library contract applies today's rule.
The program prints the important result so it can be checked against the source.
6. Common Mistakes
Small changes in reference, pointer, or
constform can change which template is more specialized, or make the call ambiguous.
7. When to Use It
Use it when reading generic call sites and predicting the selected overload.
Avoid it when it hides ownership, lifetime, type, ordering, or cost.
8. Simple Example
A value calls the general template, while a pointer calls the pointer-shaped overload because it is the more specialized match. The .cpp keeps the data fixed and avoids unrelated abstraction.
Complete sample code
Source file
cpp11/30_template_deduction_overload_resolution/main.cpp
#include <iostream>
template <typename T>
void show(T value) {
std::cout << "value=" << value << '\n';
}
template <typename T>
void show(T* pointer) {
std::cout << "pointer=" << *pointer << '\n';
}
int main() {
int number = 42;
show(number); // T is int; general overload
show(&number); // T is int; pointer overload is more specialized
show<double>(2); // explicit template argument converts to double
}
9. Key Takeaways
The feature is part of the C++11 scope used in this course.
Understand its lifetime, ownership, type, and ordering consequences.
Compile with warnings and prefer the smallest form that makes the rule obvious.
10. Self-Check Questions
Easy — What separate jobs do template argument deduction and overload resolution perform? Given
template<class T> void show(T)andtemplate<class T> void show(T*), which overload is selected for anint*?Medium — Read the small example described above. What value or state should it print, and which rule produces that result?
Hard — Find and explain the subtle bug in this situation: Small changes in reference, pointer, or
constform can change which template is more specialized, or make the call ambiguous. What is the smallest C++11-safe correction?