Templates and Generic Programming · Lesson 15 of 33
Function and Class Templates in C++
Without templates you'd write max for ints, again for doubles, again for strings. A template lets you write the code once with a placeholder type; the compiler generates a version for each type you use. The entire STL – vector<T>, map<K, V>, sort – is built from templates, so understanding them explains how the STL works and why its error messages look the way they do.
In this lesson
- Function templates and type deduction
- Class templates
- Non-type template parameters
- Specialisation, and how templates are compiled
Function templates
#include <iostream>
#include <string>
#include <vector>
template <typename T> // T is a placeholder for any type
T largest(const std::vector<T>& items) {
T best = items[0];
for (const T& x : items) if (best < x) best = x; // needs T to support <
return best;
}
template <typename A, typename B>
auto add(A a, B b) { return a + b; } // return type deduced
int main() {
std::cout << largest(std::vector<int>{4, 19, 7}) << '\n'; // T = int
std::cout << largest(std::vector<double>{2.5, 9.75, 3.0}) << '\n'; // T = double
std::cout << largest(std::vector<std::string>{"pear", "apple", "mango"}) << '\n';
std::cout << add(2, 3.5) << ' ' << add(std::string{"C"}, "++") << '\n';
std::cout << largest<int>({3, 8, 1}) << '\n'; // T given explicitly
return 0;
}
19 9.75 pear 5.5 C++ 8
What the compiler does with largest(...)
- Deduce Tfrom the argument: vector<int> → T = int
- Instantiategenerate largest<int> as real code
- Compile itcheck that int supports everything used (<, copy)
- Repeat per typelargest<double>, largest<std::string>…
Each instantiation is ordinary compiled code, so templates are as fast as hand-written versions – "zero-cost abstraction".
Class templates
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
template <typename T>
class Stack {
public:
void push(const T& value) { items_.push_back(value); }
void pop() {
if (items_.empty()) throw std::out_of_range("pop on empty stack");
items_.pop_back();
}
const T& top() const { return items_.back(); }
bool empty() const { return items_.empty(); }
std::size_t size() const { return items_.size(); }
private:
std::vector<T> items_;
};
int main() {
Stack<int> numbers;
for (int i = 1; i <= 3; i++) numbers.push(i * 10);
std::cout << "top " << numbers.top() << ", size " << numbers.size() << '\n';
Stack<std::string> history; // same code, different type
history.push("home");
history.push("courses");
history.pop();
std::cout << "back to " << history.top() << '\n';
return 0;
}
top 30, size 3 back to home
A class template needs its type argument (Stack<int>) unless the compiler can deduce it from constructor arguments – "class template argument deduction" (CTAD, C++17), which is why you can write std::vector v{1, 2, 3}; or std::pair p{1, 2.5};.
Non-type template parameters
#include <array>
#include <iostream>
template <typename T, std::size_t N> // N is a compile-time number
T sum(const std::array<T, N>& a) {
T total{};
for (const T& x : a) total += x;
return total;
}
template <int Base>
constexpr int power_of(int exp) {
int r = 1;
for (int i = 0; i < exp; i++) r *= Base;
return r;
}
int main() {
std::array<int, 4> marks{70, 85, 90, 65}; // size is part of the type
std::cout << sum(marks) << ' ' << marks.size() << '\n';
std::cout << power_of<2>(10) << ' ' << power_of<10>(3) << '\n';
return 0;
}
310 4 1024 1000
Specialisation
#include <iostream>
#include <string>
#include <type_traits>
template <typename T>
std::string describe(const T& value) { return "value " + std::to_string(value); }
template <> // full specialisation for bool
std::string describe<bool>(const bool& value) { return value ? "yes" : "no"; }
template <typename T>
std::string kind() {
if constexpr (std::is_integral_v<T>) return "integer"; // chosen at compile time
else if constexpr (std::is_floating_point_v<T>) return "floating point";
else return "other";
}
int main() {
std::cout << describe(42) << ", " << describe(true) << '\n';
std::cout << kind<long>() << ", " << kind<double>() << ", " << kind<std::string>() << '\n';
return 0;
}
value 42, yes integer, floating point, other
if constexpr (C++17) discards the branches that don't apply at compile time – often a simpler alternative to specialisation.
Templates live in headers
The compiler needs a template's full definition to generate code for each type, so templates are normally defined entirely in header files. Putting a template's body in a .cpp file causes "undefined reference" link errors for the types used elsewhere.
Practice
Try it yourself
Write a template
Pair<T>withfirst,secondand aswap()method, and use it with int and string.Show solution
#include <iostream> #include <string> #include <utility> template <typename T> struct Pair { T first, second; void swap() { std::swap(first, second); } }; int main() { Pair<int> a{1, 2}; Pair<std::string> b{"left", "right"}; a.swap(); b.swap(); std::cout << a.first << ' ' << a.second << " | " << b.first << ' ' << b.second << '\n'; return 0; }2 1 | right left
Quick check
When is template code generated?
At compile time, once for each set of template arguments used (instantiation).
Are templates slower than normal functions?
No – each instantiation is regular compiled code.
Why are templates usually defined in headers?
The compiler needs the full definition wherever the template is instantiated.
Summary
- Templates write code once for many types; the compiler instantiates each version.
- Function templates deduce types; class templates need them (or CTAD).
- Non-type parameters, specialisation and if constexpr customise templates at compile time.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.