C++ Templates
Generic programming with function and class templates
Function Templates
template <typename T> # declare template
T getMax(T a, T b) { # generic function
return (a > b) ? a : b; # return max value
}
cout << getMax(5, 10); # use with int
cout << getMax(5.5, 3.2); # use with double
Class Templates
template <typename T> # template declaration
class Box { # generic class
private:
T value; # generic type member
public:
Box(T v) : value(v) {} # constructor
T getValue() { return value; } # getter
};
Using Class Templates
Box<int> intBox(123); # create int box
Box<string> strBox("Hello"); # create string box
cout << intBox.getValue(); # prints 123
cout << strBox.getValue(); # prints Hello
Multiple Type Parameters
template <typename T, typename U> # two type parameters
class Pair {
public:
T first; # first type
U second; # second type
Pair(T f, U s) : first(f), second(s) {}
};
Pair<int, string> p(1, "One"); # mixed types