Overloaded template resolution

S

somenath

While going through the book C++ Primer (Third edition) I came across the following code from the book.

I have added the return statement and cout to trace the flow.

#include<iostream>
using namespace std;
template<class T>
T max(T t1, T t2) {
cout<<"Inside Template Fun"<<endl;
return t1;
}
//Two ordinary functions
char max(char c1,char c2)
{
cout<<"Inside char Fun "<<endl;
return c1;
}
double max(double d1, double d2 )
{
cout<<"Inside double Fun "<<endl;
return d1;
}

int main(void)
{
float fd;
max(0,fd);
return 0;
}
According to the book the compiler should be reporting error for the following reason.
"As the call (max(0,fd) ) is ambiguous ,only the ordinary functions are considered. Neither of these functions is selected as the best viable function, because the type conversions on the arguments are equally bad for both those functions: both arguments require standard conversion to match the corresponding parameter in either of the viable functions. The call is therefore ambiguous and is flagged as an error by the compiler."

But When I compile the above code in g++ I do not get any error and when Iran the program I get the following output.

“Inside double Fun”

According to me in max(0,fd); the first argument 0 is converted to doubleand fd is converted to double so the max(double d1, double d2 ) is gettingcalled and as the promotion will not cause any loss of precision so it isfine therefore there is no ambiguity exists.

Is my understanding is correct? Am I wrongly interpreting author’s point of view?
 
Ö

Öö Tiib

While going through the book C++ Primer (Third edition) I came across
the following code from the book.

Will you post it every day now? Yes, it is a defect in book. All books contain
defects and some examples do not even compile. It is anyway good book.
So contact the authors if you want them to fix the defect.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,961
Messages
2,570,131
Members
46,689
Latest member
liammiller

Latest Threads

Top