Function overloading by return type?

前端 未结 14 2258
终归单人心
终归单人心 2020-11-22 03:55

Why don\'t more mainstream statically typed languages support function/method overloading by return type? I can\'t think of any that do. It seems no less useful or reasona

相关标签:
14条回答
  • 2020-11-22 04:38

    To steal a C++ specific answer from another very similar question (dupe?):


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

    0 讨论(0)
  • 2020-11-22 04:38

    if you want to overload methods with different return types, just add a dummy parameter with default value to allow the overload execution, but don't forget the parameter type should be different so the overload logic works next is an e.g on delphi:

    type    
        myclass = class
        public
          function Funct1(dummy: string = EmptyStr): String; overload;
          function Funct1(dummy: Integer = -1): Integer; overload;
        end;
    

    use it like this

    procedure tester;
    var yourobject : myclass;
      iValue: integer;
      sValue: string;
    begin
      yourobject:= myclass.create;
      iValue:= yourobject.Funct1(); //this will call the func with integer result
      sValue:= yourobject.Funct1(); //this will call the func with string result
    end;
    
    0 讨论(0)
提交回复
热议问题