Reputation: 5920
I was wondering, is there a real technical limitation in the C++ compiler (or whatever) that causes that the return type cannot be overloaded, or is it just a design limitation inserted into the language?
Thanks!
Upvotes: 1
Views: 226
Reputation: 68728
A function call is an expression. Each expression has a context that effects how an expression is evaluated, but this information is not used in function overload resolution.
During function overload resolution the argument expressions of the function call are compared against the parameter declarations of the set of functions found when the function name is looked up. Through an extremely complicated ranking algorithm, this selects the best viable function, and then the return type of the function gives the initial type of the function call expression. Then, this return type is compared to the context to determine if a conversion is required (and if so, if it is possible and unambiguous) to adjust the return type to fit the context.
However these contexts are not simply specified by a type. Each context is specified by its own unique set of rules in the standard. So it would be extremely complicated to do overload resolution based on them.
Consider for example:
f(g(x))
Here we are doing overload resolution on f
and g
. Suppose there are 10 versions of each function- and suppose we include the context of g(x)
in overload resolution.
g(x)
is an argument to f
- so the context is "initialize one of ten different parameter types of ten different functions".
x
is an argument being compared against the 10 g
parameter lists.
So we would have to consider every possible combination of f
and g
, for a total of 100 combinations.
It's easy to see how such a scheme grows exponentially. Now consider:
f(g(h(p(x))))
That is why in C++ function overload resolution is done in two steps. For the example f(g(x))
g
is selected based on x
g(x)
is determinedf
is selected based on T
Upvotes: 1
Reputation: 80345
It is a technical limitation, if you want to call it that:
C++ types are inferred bottom-up: the type of an expression only depends on its sub-expressions, and not of the context expression(s) it appears in. So the type of the arguments of an overloaded method can be determined in order to pick which version to call, but it would be impossible to tell which method to call if there was overloading on the return type.
Example: in e1 + f(e2, e3)
, the types of e2
and e3
can be determined before the version of f
is chosen, and indeed the version of f
is only then chosen according to them. But the context does not allow to pick a version of f
according to its return type, and indeed, several types would be acceptable as return types.
Upvotes: 4