Why dont languages allow overloading of methods by return value?

前端 未结 8 519
[愿得一人]
[愿得一人] 2021-01-02 08:38

c, java and many other languages do not pay attention to return values.

int   i = func()
float f = func()
int   func() { return 5 }
float func() { return 1.3         


        
相关标签:
8条回答
  • 2021-01-02 09:04

    Most languages allow for mixed-mode operations with automatic coercion (e.g. float + int), where multiple interpretations are legal. Without coercion, working with multiple numeric types (short, int, long, float, double) would become very cumbersome; with coercion, return-type based disambigation would lead to hard-to-understand code.

    0 讨论(0)
  • 2021-01-02 09:07

    To avoid ambiguity.

    a( int )
    a( bool )
    int b()
    bool b()
    
    a( b() ) -- Which b?
    

    Here type inference has a cyclic dependency. Which b depends on which a, but which a depends on which b, so it gets stuck.

    Disallowing overloading of return types ensures that type inference is acyclic. The return type can always be determined by the parameter types, but the parameter types cannot be determined by the return type, since they may in turn be determined by the parameter types you are trying to find.

    0 讨论(0)
  • 2021-01-02 09:07

    Perl allows a certain degree of return type variation, in that functions can tell what kind of context they're being evaluated in. For instance, a function that might return an array can see that it's running in a scalar context, and just return the putative length directly, sparing the allocation and initialization of the array just to get its length.

    0 讨论(0)
  • 2021-01-02 09:13

    Let's say it was allowed, which one would this call:

    func();
    

    That may not the the full answer, but I believe that is one reason why it is not legal.

    0 讨论(0)
  • 2021-01-02 09:13

    For a C++ example, consider:

    void g(int x);
    void g(float x);
    g(func());
    

    Which of the overloaded g() functions would be called?

    0 讨论(0)
  • 2021-01-02 09:13

    Allowing these may introduce problems. For example:

    int i = func2(func());
    int func() { return 5; }
    float func() { return 1.3; }
    int func2(float a) { return a; }
    int func2(int a) { return a; }
    

    This is ambiguous.

    0 讨论(0)
提交回复
热议问题