With C++ and other languages like C# and Java, we can now use Templates with our functions and classes. A Template allows us to specify a placeholder for a data type which will be filled in later.
In the C++ Standard Template Library, there are objects like the vector that is essentially a dynamic array, but it can store any data type - we just have to tell it what it's storing when we declare a vector object:
We can write a standalone function with templated parameters or a templated return type or both. For example, here's a simple function to add two items together:
template <typename T>
T Sum( T numA, T numB )
{
return numA + numB;
}
This function can be called with any data type, so long as the data type has the + operator defined for it - so, if it were a custom class you wrote, you would have to overload the operator+ function.
What this means is that we can call Sum with integers and floats, but also with someting like a string, since strings use the + operator to combine two strings together.
More frequently, you will be using templates to create classes for data structures that can store any kind of data. The C++ Standard Template Library has data structures like vector, list, and map, but we can also write our own.
When creating our templated class, there are a few things to keep in mind:
We need to use template <typename T> at the beginning of the class declaration.
Method definitions MUST be in the header file - in this case, we won't be putting the method definitions in a separate .cpp file. You can either define the functions inside the class declaration, or immediately after it.
Method definitions also need to be prefixed with template <typename T>.
If you try to create a "TemplatedArray.hpp" file and a "TemplatedArray.cpp" file and put your method definitions in the .cpp file, then you're going to get compile errors.