C++ Templates

Write generic functions and classes.

✍️ 2 exercises in this lesson

Templates let you write code once and use it with any type. The compiler generates a version for each type you use.

  • Function template: template <typename T> T biggest(T a, T b)
  • Class template: template <typename T> class Box { T value; };

The whole Standard Library (vector<int>, map<string, int>) is built with templates.

Key Takeaways: C++ Templates

Mastering C++ Templates helps you write clean and reliable C++ code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

C++ Templates Code Example

C++
#include <iostream>
#include <string>

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

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

int main() {
    std::cout << biggest(3, 9) << "\n";
    std::cout << biggest(2.5, 1.5) << "\n";
    std::cout << biggest<std::string>("apple", "mango") << "\n";

    Box<std::string> b("Templates!");
    std::cout << b.get() << "\n";
    return 0;
}
Output
9
2.5
mango
Templates!
Run this example on your own computer. The "Get Started" lesson shows how to set it up.

C++ Templates Practice Exercises

Check what you learned in “C++ Templates”.

/ 2 solved
Fill in the blank

Declare a function template.

 <typename T>
T biggest(T a, T b) { return a > b ? a : b; }
✓ Correct! Not quite. Try again.
Multiple choice

Templates let you…

✓ Correct! Not quite. Try again.
to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services