C++ Function Templates
A function template is a pattern for a function that the compiler fills in with a chosen type. One written template can serve many types.
The same function written twice
Two functions do the same job for two types. Only the type names differ between them.
#include <iostream>
int largestInt(int a, int b) {
if (a > b) {
return a;
}
return b;
}
double largestDouble(double a, double b) {
if (a > b) {
return a;
}
return b;
}
int main() {
std::cout << "Largest int: " << largestInt(4, 9) << "\n";
std::cout << "Largest double: " << largestDouble(3.5, 7.5) << "\n";
return 0;
}One template for many types
One template replaces both functions. The same template serves an int call, a double call and a string call.
#include <iostream>
#include <string>
template <typename T>
T largest(T a, T b) {
if (a > b) {
return a;
}
return b;
}
int main() {
std::cout << "Int: " << largest(4, 9) << "\n";
std::cout << "Double: " << largest(3.5, 7.5) << "\n";
std::cout << "Word: " << largest(std::string("apple"), std::string("pear")) << "\n";
return 0;
}A third type with no new code
The template is called with a char next. The compiler writes a char version from the same pattern.
#include <iostream>
template <typename T>
T largest(T a, T b) {
if (a > b) {
return a;
}
return b;
}
int main() {
std::cout << "Int: " << largest(12, 8) << "\n";
std::cout << "Char: " << largest('a', 'z') << "\n";
return 0;
}Example
#include <iostream>
template <typename T>
T smallest(T a, T b) {
if (a < b) {
return a;
}
return b;
}
int main() {
std::cout << "Smallest int: " << smallest(14, 6) << "\n";
std::cout << "Smallest double: " << smallest(2.25, 1.5) << "\n";
return 0;
}Key points
- A template starts with a template header that names a type parameter such as T.
- The compiler writes a real function for each type the template is called with.
- Writing a version of a template for a type is called instantiation.
- The compiler can often deduce the type from the arguments at the call.
- A type can also be named in angle brackets at the call.
- A template body must work for every type it is used with.
In this example, one smallest template serves two types. The int call prints 6. The double call prints 1.5.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does the compiler do when a function template is called with a new type?