Templates and Generic Programming
Templates let one function or class work with several data types. The compiler creates the required version when the template is used.
Function Template
Generic maximum function
#include <iostream>
#include <string>
using namespace std;
template <typename T>
T larger(T a, T b)
{
return (a > b) ? a : b;
}
int main()
{
cout << larger(10, 20) << endl;
cout << larger(4.5, 3.2) << endl;
cout << larger(string("Apple"), string("Banana")) << endl;
return 0;
}Class Template
Generic Box class
template <typename T>
class Box
{
private:
T value;
public:
explicit Box(T newValue) : value(newValue) {}
T getValue() const
{
return value;
}
};Where You Already Use Templates
STL types such as vector<int>, vector<string>, and unique_ptr<Student> are template-based types.
Practice task
Write a function template named smallest that returns the smaller of two values.
Lesson Summary
Write functions and classes that work with more than one data type.