Function Overloading and Function Templates
Short drills to make the concepts stick — predict what code prints, fix a broken snippet, or write a small function. Commit to an answer before you run anything.
11.3 — Function overload resolution and ambiguous matches
Which overload does a char pick?
A char argument finds both show(int) and show(double) in scope — predict which runs and what prints.
#include <iostream>
void show(int x) { std::cout << "int:" << x << "\n"; }
void show(double x) { std::cout << "double:" << x << "\n"; }
int main()
{
char c { 'A' };
show(c);
return 0;
}Missing bool overload lets true fall through
Without a bool overload, describe(true) silently promotes to describe(int) and returns the wrong tag. Add the missing overload so the tests pass.
Edit student.cpp, then Run to check it against the tests.
11.7 — Function template instantiation
Can deduction handle mixed argument types?
The template has one type parameter T. Predict what happens when the two arguments have different types.
#include <iostream>
template <typename T>
T myMax(T a, T b)
{
return (a > b) ? a : b;
}
int main()
{
std::cout << myMax(3, 4.5) << "\n";
return 0;
}11.8 — Function templates with multiple template types
Return type narrows the result
The template multiplies two values of possibly different types — but it silently loses the fractional part when T is int. Fix the return type so the function returns whatever the multiplication actually produces.
Edit student.cpp, then Run to check it against the tests.
11.6 — Function templates
Write a myMin function template
Implement a function template myMin that returns the smaller of two values of the same type.
Edit student.cpp, then Run to check it against the tests.