{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

lecture9 notes - 6.096 Introduction to C Massachusetts...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
6.096 Introduction to C++ January 24th, 2011 Massachusetts Institute of Technology John Marrero Lecture 9 Notes: Advanced Topics I 1 Templates We have seen that functions can take arguments of specific types and have a specific return type. We now consider templates, which allow us to work with generic types. Through templates, rather than repeating function code for each new type we wish to accommodate, we can create functions that are capable of using the same code for different types. For example: 1 int sum( const int x, const int y) { 2 return x + y; 3 } For this function to work with doubles, it must be modified to the following: 1 double sum ( const double x, const double y) { 2 return x + y; 3 } For a simple function such as this, it may be a small matter to just make the change as shown, but if the code were much more complicated, copying the entire function for each new type can quickly become problematic. To overcome this we rewrite sum as a function template. The format for 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 T s 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 main() { 2 cout << sum< int >(1, 2) << endl; 3 cout << sum< float >(1.21, 2.43) << endl; 4 return 0; 5 } This program prints out 3 and 3.64 on separate lines.
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
The identifier can be used in any way inside the function template, as long as the code makes sense after identifier is replaced with some type. It is also possible to invoke a function template without giving an explicit type, in cases where the generic type identifier is used as the type for a parameter for the function. In the above example, the following would also have been valid: 1 int main() { 2
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}