Templates
Templates allow the programmer to create a generic function or class that can work with a variety of data types. The syntax is as follows,
template <class ItemType>
void Foo(ItemType data)
{
//...
}
ItemType is a user-defined name that is used to represent a generic data type in the function. The following syntax is used to call the function with a specific data type.
Foo<int>(25); //calling a function
Calc<int> class_calc; //create a class object
Any data type can be used in place of int, and then passed as the first parameter of the function, or be used in the class. The compiler makes different versions of templated functions and classes, replacing ItemType (or another name that you can define) with the data type being used. Note, you may also include more than one object to template. For example,
template <class Item1, class Item2>
void function Foo(Item1 data, Item2 pos)
{
//...
}
An explicit version of the function can be defined for specific data types as well.
template <class ItemType>
template <class ItemType>template <class ItemType>
void function Foo(ItemType data);
void function Foo<int>(ItemType data)
{
cout << "This function works with int variables";
}
void function Foo<char>(ItemType data)
{
cout << "This function works with char variables";
}