lecture9 notes

The format for declaring a function template is

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: or declaring a function template is: template <class identifier> function_declaration; or template <typename identifier> function_declaration; Both forms are equivalent to one another, regardless of what type identifier ends up being. We can then use identifier to replace all occurrences of the type we wish to generalize. So, we rewrite our sum function: 1 template <typename T> 2 T sum(const T a, const T b) { 3 return a + b; 4 } Now, when sum is called, it is called with a particular type, which will replace all Ts in the code. To invoke a function template, we use: function_name <type> (parameters); Here is an example main function using the above sum function template: 1 int 2 3 4 5 } main() { cout << sum<int>(1, 2) << endl; cout << sum<float>(1.21, 2.43) << endl; return 0; This program prints out 3 and 3.64 on separate lines. The identifier can be used in any way inside the function template, as long as the code makes sense after identi...
View Full Document

Ask a homework question - tutors are online