C++ template Keyword
Example
Create a function template that works with both int and double:
template <typename T>
T add(T a, T b) {
return a + b;
}
int main() {
cout << add<int>(5, 3) << "\n";
cout << add<double>(2.5, 1.5);
return 0;
}
Definition and Usage
The template keyword declares a template. A template is a function or class that works with different data types, so you only need to write the code once.
In template <typename T>, T is a placeholder for a data type. In the example above, add<int>(5, 3) uses int for T, and add<double>(2.5, 1.5) uses double.
Related Pages
Read more about templates in our C++ Templates Tutorial.