Sunday, March 15, 2015

Post #11 - function templates

Function templates use the same function to accept multiple types of data without having to recreate the function again for each needed data type. Overloaded functions share the same name but have different parameter lists for each one, and can work with different data while making different function names in the program easy to remember.

An overloaded function prototype:
void ShowBook(int array[]);
void ShowBook(string, float);

ShowBook needs to have two calls to it in main that have a different number of variables in the parentheses, otherwise one will be called twice and passed an incompatible data type or the wrong number of arguments.

cout << "Chapters of book: " << ShowBook(volume);
cout << "Title and price of book: " << ShowBook(title, price);

The function definitions for each are considered as two separate functions.
void ShowBook(int v[])
{ //body of function }
void ShowBook(string t, float p)
{ //body of function }

A function template can cause a function to be able to work with any data type passed to it in main, if the header template <class name> is put above the function call and function definition to define the created typeholder name, which is not a new data type but acts as a container to accept any data type. name can be anything you want to name the typeholder, typically T or type is used to prevent confusion though. It goes before the variable passed to the function whose data type could become several different types over the run of the program.

template <class money>
int BookPrice(money books);

books can now accept any type given by main:

int volume1 = 5;
float volume2 = 3.99;
cout << "Price in dollars: $" << BookPrice(volume1);
cout << "Price in dollars & cents: $" << BookPrice(volume2);

The function definition should also have the template class put before it as well, otherwise the reference to money as a typeholder will not be understood by the compiler.

No comments:

Post a Comment