Return type polymorphism in C-like languages

后端 未结 5 568
梦如初夏
梦如初夏 2021-01-17 14:46

Why don\'t we see C-like languages that allow for callables with polymorphism in the return type? I could see how the additional type inference would be a hurdle, but we hav

5条回答
  •  独厮守ぢ
    2021-01-17 15:35

    If by "return type polymorphism" you mean overloading based on the return value type, I'm not sure about other languages, but for C++ here's the answer (pretty much from the horse's mouth):

    Function return types don't come into play in overload resolution simply because Stroustrup (I assume with input from other C++ architects) wanted overload resolution to be 'context independent'. See 7.4.1 - "Overloading and Return Type" from the "C++ Programming Language, Third Edition".

    The reason is to keep resolution for an individual operator or function call context-independent.

    They wanted it to be based only on how the overload was called - not how the result was used (if it was used at all). Indeed, many functions are called without using the result or the result would be used as part of a larger expression. One factor that I'm sure came into play when they decided this was that if the return type was part of the resolution there would be many calls to overloaded functions that would need to be resolved with complex rules or would have to have the compiler throw an error that the call was ambiguous.

    And, Lord knows, C++ overload resolution is complex enough as it stands...

提交回复
热议问题