{[ promptMessage ]}

Bookmark it

{[ promptMessage ]}

Template Functions &amp; Classes

# Template Functions &amp; Classes - Lecture 7 Template...

This preview shows pages 1–4. Sign up to view the full content.

1 Lecture 7: Template Functions & Classes PIC 10B Todd Wittman Flexible Parameter Types box4 In general when we write a function we have to know the type of each parameter we receive. void print (int x, double y, string z) { cout<<"x= " << x << "\ny= " << y << "\nz= " << z; return; } box4 But what if we don't know ahead of time that x is an int, y is a double, and z is a string? box4 One solution is to overload the function many different ways. void print (int x, int y, int z); void print (string x, int y, double z); void print (double x, double y, int z); box4 But this sux. box4 A better solution would be to write a single function with flexible parameter types.

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

View Full Document
2 Sec 16.1 : Template Functions box4 A template function sets up flexible parameter types. box4 The type is defined by the call, not the function. box4 We create our own data type T right above the function: template <typename T> void my_function (T parameter) { ... box4 T acts like a dummy data type. box4 We usually use a single capital letter for templated types. box4 Then my_function can receive different parameter types. my_function(-2); // T is int my_function (3.14); // T is double my_function("yoda"); // T is string my_function(false); // T is bool my_function(myProduct); // T is Product Template Functions box4 Can also create multiple tempated types: template <typename T1, typename T2, ...> box4 So our print function could be rewritten: template <typename A, typename B, typename C> void print (A x, B y, C z) { cout<<"x= " << x << "\ny= " << y << "\nz= " << z; return; } box4 Note the template is part of the function declaration. box4 The type is now defined by the function call. string s="Yoda"; IntMatrix M(3,4); int v=42; print (s, M, v); //A is string, B is IntMatrix, C is int box4 What is the output?
3 Be Careful of Different Cases box4 In order for the print function to work, it assumes that the output push << is defined for each type A, B, C. string s="Yoda"; IntMatrix M(3,4); vector<int> v(10); print (s, M, v); //A is string, B is IntMatrix, C is vector<int> box4 The string and IntMatrix will print, because we defined << for our IntMatrix class.

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

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

{[ snackBarMessage ]}

### Page1 / 10

Template Functions &amp; Classes - Lecture 7 Template...

This preview shows document pages 1 - 4. Sign up to view the full document.

View Full Document
Ask a homework question - tutors are online