Reputation: 3143
In C++, Why function overloading not implemented on the basis of return type?
Upvotes: 1
Views: 408
Reputation: 45
When calling a function, its return type is not involved. So it would be meaningless to implement function overloads with different return types.
Upvotes: 0
Reputation: 153919
Because C++ has implicit conversions which make it more or less impossible most of the time, e.g.:
int f();
char f();
double d = f();
It's possible to simulate overloading on the return type some of the time, by using a proxy object:
int doFInt();
char doFChar();
struct Proxy
{
template<typename T> operator T() const
{
return static_cast<T>(doFInt());
}
};
template<>
Proxy::operator char() const { return doFChar(); }
Proxy f();
double d = f(); // Calls doFInt().
About the only time something like this is worth the bother, however, is when it can be made truely generic; something like a getAttribute function where the attribute is always stored as a string, and the generic form of the function uses boost::lexical_cast to convert to the target type.
Upvotes: 1
Reputation: 116266
Because it is legal to ignore return values, thus the compiler would not always be able to realistically decide which overload to invoke.
Consider
void foo();
int foo();
long foo();
...
foo(); // which function to call here???
But even if the return value is assigned, it may not be possible to choose between equivalent overloads when a conversion is required:
double d = foo(); // and here???
Upvotes: 15
Reputation: 22094
Consider the case:
double Fun()
{
}
int Fun()
{
}
Since it's not compulsory to assign a return value from a function, a call to Fun()
would be ambiguous since the compiler wont know which Fun()
to call.
Upvotes: 1
Reputation: 2621
Because the compiler would not always been able to decide which function to select.
Upvotes: 0