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?
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?