CodeBlanks Logo Icon CodeBlanks

Template functions

Learn to define and call template functions.

Template function call

A template function is called like a normal function. In max(3, 5) the compiler deduces T=int. You can also specify the type: max<double>(3.0, 5.0).

Example: template <typename T> T max(T a, T b) { return a > b ? a : b; }. Here a > b ? a : b is a ternary that returns the larger value. The call max(3, 5) yields 5. The compiler produces a separate version for each call; there is no run-time overhead.

Type deduction limits

Type deduction doesn't always work. In max(3, 5.0) the compiler cannot decide whether T is int or double; the two arguments have different types.

The fix is to specify the type: max<double>(3, 5.0) runs with T=double; 3 is converted to double. Likewise max<int>(3, 5.0) converts 5.0 to int. When deduction is ambiguous, an explicit type is required.

Practice Write the add template

Write template <typename T> T add(T a, T b) that returns a + b. In main call std::cout << add(3, 4) << std::endl;.

Starter code

main.cpp
#include <iostream>

// write the add template function: T add(T a, T b)

int main() {
    // call add and print the result
    return 0;
}

Sample solution

main.cpp
#include <iostream>

template <typename T>
T add(T a, T b) {
    return a + b;
}

int main() {
    std::cout << add(3, 4) << std::endl;
    return 0;
}

Expected output

7

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match call to meaning

Term Meaning
max(3, 5) T=int deduced
max<double>(3.0, 5.0) Explicit type
max("a", "b") T=const char*
max<int>(3, 5) Explicit int

2 What does T become in the call max(3, 5)?

main.cpp
template <typename T> T max(T a, T b);
  • double
  • int Correct answer
  • const char*
  • void

Explanation: 3 and 5 are int literals, so T=int is deduced.

3 Complete the explicit-type call

Question
int result = max____(3, 5);
Answer
int result = max<int>(3, 5);

Explanation: max<int>(3, 5) specifies the type as int explicitly.

All lessons in Intermediate