There are three absolute value functions defined in various header files. These are abs, fabs, and labs. Write a template function that subsumes all three of these functions into one template function.
What will be an ideal response?
This is a solution complete with a test framework and a work-around for Microsoft VC++ 6.0 before patch level 5.
```
#include
using namespace std;
//requires operator > and unary operator- be defined and //comparison to the value of the default c-tor be //meaningful.
//The call to T() is a call to the default constructor //for the type T. For primitive types such as int or //double, this is 0 of the type. For other types, it is //what the default constructor generates.
template
T absolute( T src)
{
if( src > T())//
return src;
return -src;
}
class A
{
public:
A():i(0){}
A(int new_i):i(new_i) {}
A operator=(const A&x);
A operator-() {return A(-i);}
friend bool operator>(const A& lhs, const A& rhs);
friend
ostream& operator<<(ostream& out,const A& rhs);
private:
int i;
};
bool operator>(const A& lhs, const A& rhs)
{
return lhs.i > rhs.i;
}
ostream& operator<<(ostream& out,const A& rhs)
{
out << rhs.i;
return out;
}
A A::operator=(const A& rhs)
{
i = rhs.i;
return A(i);
}
int main()
{
int a = -1;
cout << absolute(a) << endl;
A one(1);
A minusOne(-1);
cout << one << endl;
cout << absolute(one) << endl;
cout << absolute(minusOne) << endl;
}
```
The student is encouraged to go to the Microsoft web site and download the patch for their copy of VC++. This will avoid the problem completely. For the time bein, the work-around for VC++ 6.0 before patch level 5 is to put definitions of operators overloaded as friends of the class inside the class. complete with the friend keyword. This code works fine with Borland and g++ as it is.
You might also like to view...
Case-Based Critical Thinking QuestionsCase 2As Dan creates a new table for the database he is building to track the budget for his small business, he is struck by how many different data types he will be using. He turns to his friend Giovanni for a quick refresher on each of the data types and which one is most appropriate for a particular need. Dan has a field that indicates whether or not a particular vendor is a bonded agent. Which data type will Giovanni recommend as a good match for this need?
A. Binary B. Integer C. Yes/No D. Lookup Wizard
Which of the following statements is FALSE about the status bar in Office 2013?
A) The status bar is located at the bottom of the Office 2013 window. B) Slide number and total slide information are displayed in PowerPoint. C) Summary information is displayed in Excel. D) Contents viewable on the status bar are standard in all Office applications.
To hide the details for a group in a Pivot Table, you can ________ it
Fill in the blank(s) with the appropriate word(s).
This type of e-commerce is a manufacturer-supplier relationship
What will be an ideal response?