A Template is a simple and a very powerful statement in C++. A Template Function may have multiple template parameter types, and the function can still use regular non-templated types. In a previous post, about Function Overloading, we had two add() functions working with integer and float numbers, in that example we can say add() function is overloaded with int and float parameter types, and with the same body.
This add() function can be overloaded for a lot of types, and it could make sense for all of them to have the same body. For cases such as this, C++ can define functions with generic types, known as Function Templates. Defining a function template follows the same syntax as a regular function, except that it is preceded by the template keyword and a series of template parameters enclosed with < and > angle brackets. Here is a generic form of a template usage,
1 2 3 |
template <template-parameters> function-declaration |
The template parameters are a series of parameters separated by commas. These parameters can be generic template types by specifying either the class
or type name keyword followed by an identifier. This identifier can then be used in the function declaration as if it was a regular type. For example, in general usage, our previous add() function could be defined as,
1 2 3 4 5 6 7 |
template <class TempType> TempType add (TempType a, TempType b) { return a+b; } |
Templates are a powerful and versatile feature because of variable type can be defined during usage. Template functions may have multiple template parameters, and the function can still use regular non-templated types. Here is the full example how to use these template functions,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> template <class TempType> TempType add (TempType a, TempType b) { TempType result; result = a + b; return result; } int main() { int a = 500, b = 300, c; float x = 2.0, y = 0.5, z; c = add <int> (a, b); z = add <float> (x, y); std::cout << c << '\n'; std::cout << z << '\n'; getchar(); return 0; } |
Non-type Template Arguments
In some cases, the template arguments may include expressions of a particular type instead of being introduced by class or type name only,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> template <class TempType, int b> TempType add (TempType a) { return a + b; } int main() { std::cout << add<int,9>(100) << '\n'; std::cout << add<int,8>(100) << '\n'; getchar(); return 0; } |
Here , the second parameter of this add() function template is of type int
. It just looks like a regular function parameter, and can actually be used just like one.
Get started building powerful apps with C++Builder!
Design. Code. Compile. Deploy.
Start Free Trial
Free C++Builder Community Edition