Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Let\'s say you have a function int calc (int operand1, int operand2, char op) wh

ID: 3821738 • Letter: L

Question

Let's say you have a function int calc (int operand1, int operand2, char op) where op is either'+' or. Instead of overloading this function for each numerical datatype in C++ (e.g. also defining it for float, double, etc., you want to create a generic function that is far more flexible. In the space below, define calc as a template function. If op is neither '+' nor '-', print an error message on cerr and call the system function exit (1); (you may assume that #include has already been done.) Note that once we've covered exceptions, that would be a better approach than the cerr/exit technique. Grading: for correct template function header for correctly handling the error for function body being correct for non-error case.

Explanation / Answer

#include<iostream>

#include<cstdlib>

using namespace std;


template <class T>

T calc (T operand1, T operand2, char op) {

T result;

if (op == '+')

   result = operand1 + operand2;

else if (op == '-')

   result = operand1 - operand2;

else {

   cerr<<"Operator ("<<op<<") not supported. Exiting";

   exit(1);

}

   

return (result);

}

int main() {

int i=5, j=6, k;

long l=1, m=5, n;

k=calc<int>(i,j,'+');

cout << k << endl;

n=calc<long>(l,m,'+');

cout << n << endl;

n=calc<long>(l,m,'*');

cout << n << endl;

return 0;

}

Here you go champ. You now have the code that should meet your needs. I also implemented the code using the main function to demonstrate the working of the code. Umm.. I haven't put any comments because the code is very easy. If you face any problem with the same, please feel free to comment below. I shall be glad to help you with the code.