Return type polymorphism in C-like languages

后端 未结 5 525
梦如初夏
梦如初夏 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:36

    i would love to see this feature in some language, not only so that function foo could return a double or an int or a string, but also so that foo could return a structure or objects of different classes. Disambiguating calls would be fairly trivial - if the call is ambiguous, require a cast to select the return type desired. Example:

    string s = foo();    //foo returns a string
    double x = foo();    //foo returns a double
    int i = foo();       //foo returns an integer
    float f = (float)(int)foo();    //call the int foo and convert to float
    

    in addition

    Animal a = fooFactory();    //fooFactory returns an Animal
    Plant p = fooFactory();     //foofactory returns a Plant
    

    these situations do not come up very often, but when they do the workaround is often fairly ugly...

提交回复
热议问题