Overloading by return type

前端 未结 11 1727
我在风中等你
我在风中等你 2020-11-22 07:07

I read few questions here on SO about this topic which seems yet confusing to me. I\'ve just begun to learn C++ and I haven\'t studied templates yet or operator overloading

相关标签:
11条回答
  • 2020-11-22 07:34

    Resurrecting an old thread, but I can see that nobody mentioned overloading by ref-qualifiers. Ref-qualifiers are a language feature added in C++11 and I only recently stumbled upon it - it's not so widespread as e.g. cv-qualifiers. The main idea is to distinguish between the two cases: when the member function is called on an rvalue object, and when is called on an lvalue object. You can basically write something like this (I am slightly modifying OP's code):

    #include <stdio.h>
    
    class My {
    public:
        int get(int) & { // notice &
            printf("returning int..\n");
            return 42;
        }
        char get(int) && { // notice &&
            printf("returning char..\n");
            return 'x';
        };
    };
    
    int main() {
        My oh_my;
        oh_my.get(13); // 'oh_my' is an lvalue
        My().get(13); // 'My()' is a temporary, i.e. an rvalue
    }
    

    This code will produce the following output:

    returning int..
    returning char..
    

    Of course, as is the case with cv-qualifiers, both function could have returned the same type and overloading would still be successful.

    0 讨论(0)
  • 2020-11-22 07:39

    No, you can't overload by return type; only by parameter types, and const/volatile qualifiers.

    One alternative would be to "return" using a reference argument:

    void get(int, int&);
    void get(int, char&);
    

    although I would probably either use a template, or differently-named functions like your second example.

    0 讨论(0)
  • 2020-11-22 07:41

    There is no way to overload by return type in C++. Without using templates, using get_int and get_char will be the best you can do.

    0 讨论(0)
  • 2020-11-22 07:43

    You can't overload methods based on return types. Your best bet is to create two functions with slightly different syntax, such as in your second code snippet.

    0 讨论(0)
  • 2020-11-22 07:46

    You can think this way:

    You have:

      int get(int);
      char get(int);
    

    And, it is not mandatory to collect the return value of the function while invoking.

    Now, You invoke

      get(10);  -> there is an ambiguity here which function to invoke. 
    

    So, No meaning if overloading is allowed based on the return type.

    0 讨论(0)
  • 2020-11-22 07:46

    As stated before, templates are overkill in this case, but it is still an option worth mentioning.

    class My {
    public:
        template<typename T> T get(int);
    };
    
    template<> int My::get<int>(int);
    template<> char My::get<char>(int);
    
    0 讨论(0)
提交回复
热议问题