Chapter 11 · Function Overloading and Function Templates
Practice · Chapter 11

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

predict

Which overload does a char pick?

A char argument finds both show(int) and show(double) in scope — predict which runs and what prints.

C++
#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;
}
Choose the output
fix

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.

student.cppeditable

Edit student.cpp, then Run to check it against the tests.

11.7 — Function template instantiation

predict

Can deduction handle mixed argument types?

The template has one type parameter T. Predict what happens when the two arguments have different types.

C++
#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;
}
Choose the output

11.8 — Function templates with multiple template types

fix

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.

student.cppeditable

Edit student.cpp, then Run to check it against the tests.

11.6 — Function templates

write

Write a myMin function template

Implement a function template myMin that returns the smaller of two values of the same type.

student.cppeditable

Edit student.cpp, then Run to check it against the tests.