Function overloading by return type?

前端 未结 14 2243
终归单人心
终归单人心 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:24

    Good answers! A.Rex's answer in particular is very detailed and instructive. As he points out, C++ does consider user-supplied type-conversion operators when compiling lhs = func(); (where func is really the name of a struct). My workaround is a bit different - not better, just different (although it's based on the same basic idea).

    Whereas I had wanted to write...

    template  inline T func() { abort(); return T(); }
    
    template <> inline int func()
    { <> }
    
    template <> inline double func()
    { <> }
    
    .. etc, then ..
    
    int x = func(); // ambiguous!
    int x = func(); // *also* ambiguous!?  you're just being difficult, g++!
    

    I ended up with a solution that uses a parameterized struct (with T = the return type):

    template 
    struct func
    {
        operator T()
        { abort(); return T(); } 
    };
    
    // explicit specializations for supported types
    // (any code that includes this header can add more!)
    
    template <> inline
    func::operator int()
    { <> }
    
    template <> inline
    func::operator double()
    { <> }
    
    .. etc, then ..
    
    int x = func(); // this is OK!
    double d = func(); // also OK :)
    

    A benefit of this solution is that any code which includes these template definitions can add more specializations for more types. Also you can do partial specializations of the struct as needed. For example, if you wanted special handling for pointer types:

    template 
    struct func
    {
        operator T*()
        { <> } 
    };
    

    As a negative, you can't write int x = func(); with my solution. You have to write int x = func();. You have to explicitly say what the return type is, rather than asking the compiler to suss it out by looking at type conversion operators. I would say that "my" solution and A.Rex's both belong in a pareto-optimal front of ways to tackle this C++ dilemma :)

提交回复
热议问题