Templates
template <typename T> lets a function work with a type decided at the call site, not when it's written. Unlike Rust's trait-bounded generics, a C++ template is duck-typed: the compiler just needs the operations you actually use inside the function body (here, > and copying) to be valid for whatever T turns out to be.
main.cpp
Try it yourself →#include <iostream>
using namespace std;
template <typename T>
T maxOf(T a, T b) {
return (a > b) ? a : b;
}
int main() {
cout << maxOf(3, 7) << endl;
cout << maxOf(2.5, 1.5) << endl;
return 0;
}Output
7 2.5
Class templates
A class can be templated too — Box<T> below works for any type T, with the specific type filled in wherever the class is used, such as Box<int> or Box<string>.
main.cpp
Try it yourself →#include <iostream>
#include <string>
using namespace std;
template <typename T>
class Box {
private:
T value;
public:
Box(T v) : value(v) {}
T getValue() const {
return value;
}
};
int main() {
Box<int> intBox(42);
Box<string> strBox("hello");
cout << intBox.getValue() << endl;
cout << strBox.getValue() << endl;
return 0;
}Output
42 hello
Next: STL containers and iterators — std::map, std::set, and iterating any container the same way.
Practice exercise
Write a template function first<T>(T a, T b) that returns a, then call first(10, 20) and print the result.