Templates

Write one function or class that works for any type; the compiler makes a version per type used.

C++ · beginner · 7 min · 14 steps · free

What you'll learn

templates.cpp

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

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

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

int main() {
    int i = biggest(3, 9);                         // T is int
    double d = biggest(2.5, 1.5);                  // T is double
    Box<string> label("fragile");                  // T is string
    string text = label.get();
    cout << i << " " << d << " " << text << endl;
    return 0;
}

Step by step

  1. biggest(3, 9): the compiler makes an int version.
  2. The method returns a > b ? a : b.
  3. biggest<int>() has finished, so its variables are gone. The value it returned, 9, is stored in i.
  4. And a double version for biggest(2.5, 1.5).
  5. The method returns a > b ? a : b.
  6. biggest<double>() has finished, so its variables are gone. The value it returned, 2.5, is stored in d.
  7. Box<string>: T is string.
  8. Box() has finished, so its variables are gone. label is created on the stack with the value {item: "fragile"}.
  9. C++ calls get(). It gets its own variables on the stack.
  10. get() has finished, so its variables are gone. The value it returned, "fragile", is stored in text.
  11. It prints 9 2.5 fragile.
  12. The method returns 0.
  13. The destructor ~Box() runs, because the object is going away.
  14. 9 2.5 fragile.

Common mistakes

Best practices

Key takeaways

Check yourself

biggest(3, 9) has T = ?

Answer: int. Deduced from the arguments.

vector<int> is?

Answer: A class template used with int. vector is a template.

·

More in The Standard Library