11.1 — Templates: code for any type
Read one box at a time. No rush.
Write once, use with any type#
In 6.6 — Same name, different inputs (overloading) we wrote largest twice: once for int, once for double. A template lets us write it once.
C++▶ Run
template <typename T>T largest(T a, T b){ return (a > b) ? a : b;} int main(){ std::cout << largest(3, 9) << '\n'; // int std::cout << largest(2.5, 1.5) << '\n'; // double std::cout << largest<std::string>("ant", "bee") << '\n'; // string return 0;}How it works#
template <typename T>= "Tstands for some type, to be filled in later".- When you call
largest(3, 9), C++ sees twoints and makes anintversion for you.
Key idea
You've already used templates! std::vector<int> is a template — the <int> fills in the type.
Class templates#
Your own types can be templates too:
C++
template <typename T>struct Pair{ T first {}; T second {};}; Pair<int> scores { 90, 85 };Pair<std::string> names { "Ana", "Ben" };Tip: press ← / → to move between lessons, / to search.