+ 2

76.2 Practice - Function Templates

You need to write a function, which returns the maximum of its two parameters, and it should work for different data types (integers, doubles, etc.) Create a function template called myMax(), which takes two parameters and returns the larger one, so that the code in main works as expected. Sample Input 4.2 8.1 Sample Output 8.1 *Remember, the syntax for declaring a template function is template <class T> My code is below. I have run out of ideas. Please help.

6th Jan 2022, 12:16 AM
Chin Eu
Chin Eu - avatar
7 Answers
+ 2
#include <iostream> using namespace std; template<class T> T myMax(T a, T b) { return a > b ? a : b; } int main () { double x, y; cin>>x>>y; int a, b; cin>>a>>b; cout << myMax(x, y) << endl; cout << myMax(a, b) << endl; }
20th Dec 2022, 2:38 PM
James Joshua
James Joshua - avatar
+ 2
#include <iostream> using namespace std; template<class T, class X> T myMax(T a, X b) { return (T)(a > b ? a : b); } int main () { double x; int y; cin>>x>>y; cout << myMax(x, y) << endl; } This is a correct answer and runit code
17th Jun 2023, 4:53 AM
Mahesh Kushwaha
+ 1
#include <iostream> using namespace std; //your code goes here template <class T> T myMax(T a, T b) { return (a > b ? a : b); } int main () { double x, y; cin>>x>>y; int a, b; cin>>a>>b; cout << myMax(x, y) << endl; cout << myMax(a, b) << endl; } Good Luck
26th Jan 2022, 5:25 AM
Muhammad Alif Deva Rizqon
Muhammad Alif Deva Rizqon - avatar
0
#include <iostream> using namespace std; //your code goes here template <class T> T myMax(int a, int b) { return (a < b ? a : b); } int main () { double x, y; cin>>x>>y; int a, b; cin>>a>>b; cout << myMax(x, y) << endl; cout << myMax(a, b) << endl; }
6th Jan 2022, 12:16 AM
Chin Eu
Chin Eu - avatar
0
mabey the parameters should be of the template type as well... your code only takes integers as arguments.
6th Jan 2022, 12:26 AM
Slick
Slick - avatar
0
#include <iostream> using namespace std; template<class T> T myMax(T a, T b) { return a > b ? a : b; } int main () { double x, y; cin>>x>>y; int a, b; cin>>a>>b; cout << myMax(x, y) << endl; cout << myMax(a, b) << endl; }
15th Nov 2022, 11:48 AM
Pooja Patel
Pooja Patel - avatar
- 2
6th Jan 2022, 9:08 AM
Chin Eu
Chin Eu - avatar