C++ Templates

Templates let you write generic code that works with any type.

C++
#include <iostream>
using namespace std;

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

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

int main() {
    cout << maxOf(3, 9) << " " << maxOf(2.5, 1.5) << " " << maxOf<string>("apple", "mango") << endl;
    Box<int> b(42);
    cout << b.get() << endl;
}
9 2.5 mango 42

Exception Handling

C++
#include <iostream>
#include <stdexcept>
using namespace std;

double divide(double a, double b) {
    if (b == 0) throw runtime_error("Division by zero");
    return a / b;
}

int main() {
    try {
        cout << divide(10, 2) << endl;
        cout << divide(1, 0) << endl;
    } catch (const exception &e) {
        cout << "Error: " << e.what() << endl;
    }
}
5 Error: Division by zero
Track your progress through the C++ course