Lesson 159 +10 XP

Multiple Template Types

Multiple Template Types

A template can take more than one type parameter, which is handy whenever a function must handle arguments of different kinds in the same call.

Declaring two types

template <typename T, typename U>
void printPair(T a, U b) {
  cout << a << " " << b;
}

T and U are independent placeholders. Each gets its own concrete type at the call.

Different types together

using namespace std;

int main() {
  printPair(1, 2.5);     // T = int, U = double
  printPair("hi", 3);    // T = const char*, U = int
  return 0;
}

The two parameters never have to match. An int and a double can share the same function happily.

A helper example

template <typename T, typename U>
bool sameSize(T a, U b) {
  return sizeof(a) == sizeof(b);
}

sameSize uses the sizeof operator to compare how much memory each argument takes, whatever their types.

Formatting the header

The parameters are a comma-separated list inside angle brackets, one typename per type. The order of the two placeholders implies which arguments map to T and to U.

TL;DR

  • template <typename T, typename U> declares a template with two types.
  • Each type parameter fills in independently from the arguments.
  • Multi-type templates handle different kinds of values at the same time.
  • Each combination of types creates its own specialization.