lecture9 notes

It is also possible to invoke a function template

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: fier 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 2 3 4 5 } main() { cout << sum(1, 2) << endl; cout << sum(1.21, 2.43) << endl; return 0; Templates can also specify more than one type parameter. For example: 1 2 3 4 5 6 7 8 9 10 11 12 #include <iostream> using namespace std; template <typename T, typename U> U sum(const T a, const U b) { return a + b; } int main() { cout << sum<int, float>(1, 2.5) << endl; return 0; } This program prints out 3.5. In this case we can also call sum by writing sum(1, 2.5). Class templates are also possible, in much the same way we have written function templates: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 #include <iostream> using namespace std; template <typename T> class Point { private: T x, y; public: Point(const T u, const T v) : x(u), y(v) {} T getX() { return x; }...
View Full Document

This document was uploaded on 03/18/2014 for the course EECS 6.096 at MIT.

Ask a homework question - tutors are online