I completely don't understand any thing about templates. I read books on C++ to help but i just don't get what are they for and how to use them i thought they were for classes to have one class but for many types but am still not certain.
Can some one help me understand how to use them and what they are for.
Templates enable code reuse, by allowing a function or class to work with different types.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// A function example:
// Swap value1 with value2
template <class T>
void swap ( T& value1, T& value2)
{
T temp = value1;
value1 = value2;
value1 = temp;
}
// ... many lines later in another function
int v1 = 5;
int v2 = 20;
swap(v1, v2); // now v2 = 5 and v1 = 20
// strings and other types can be swapped too
Containers are often implemented as templates to allow them to work with multiple types.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
int main(void)
{
// a vector is basically an array
vector<int> intVector;
intVector.push_back(1); // add the number 1 to the array
intVector.push_back(2); // add 2 to the array
cout << intVector[0] << " " << intVector[1] << endl; // prints: 1 2
// a vector of strings
vector<string> strVector;
strVector.push_back("hello");
strVector.push_back("world!");
cout << strVector[0] << " " << strVector[1] << endl; // prints: hello world!
return 0;
}
Disclaimer: This code will not work if it's just copy-pasted; additional libraries must be included. I did not compile this code so there my be syntax or other errors.