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.

Computer Science & Information Technology

You might also like to view...

A scrum team usually consists of _________.

A. ?less than a dozen people B. ?twelve to fifteen people C. fifteen to twenty people D. more than twenty people

Computer Science & Information Technology

A disk management software utility named ____________________ searches your hard drive for unnecessary files to delete.

Fill in the blank(s) with the appropriate word(s).

Computer Science & Information Technology