Operator Overloading and Templates
You can define how operators such as + and << work for your own class. Templates write one function or class that works with many types. The compiler generates the right version for each type you use.
Example
#include <iostream>
using namespace std;
struct Point {
int x, y;
Point operator+(const Point& o) const { return {x + o.x, y + o.y}; }
};
template <typename T>
T biggest(T a, T b) { return a > b ? a : b; }
int main() {
Point p = Point{1, 2} + Point{3, 4};
cout << p.x << "," << p.y << endl;
cout << biggest(3, 9) << " " << biggest(2.5, 1.5) << " " << biggest(string("a"), string("b")) << endl;
}Result
4,6 9 2.5 b
Exercise
Declare a generic function.
<typename T> T id(T x) { return x; }Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.