WeCodeAcademy

C++ Templates

Templates let one function or class work with many types. The compiler writes the right version for each type you use.

ExampleC++
#include <iostream>
#include <string>
using namespace std;

template <typename T>
T largest(T a, T b) {
  return (a > b) ? a : b;
}

template <typename T>
class Box {
  T value;
 public:
  Box(T v) : value(v) {}
  T get() const { return value; }
};

int main() {
  cout << largest(3, 9) << endl;
  cout << largest(2.5, 1.5) << endl;
  cout << largest(string("apple"), string("banana")) << endl;

  Box<int> a(42);
  Box<string> b("text");
  cout << a.get() << " " << b.get() << endl;
  return 0;
}
Output
9
2.5
banana
42 text
Quick check

What does a template do?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.