Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't RHR functions be overloaded?

Tags:

c++

c++11

I could see something like the following being useful:

class A {
public:
   const vector<int>& vals() const {
       return val;
   }

   vector<int> vals() && {
       return std::move(val);
   }
private:
    vector<int> val;
}

But I get a compiler error with g++:

error: ‘vector<int> A::vals() &&’ cannot be overloaded

I would think you'd be able to do the same sort of overloading that you can with const functions. This would be less useful for the above accessor, and more useful for operators.

like image 594
IdeaHat Avatar asked Jan 05 '15 14:01

IdeaHat


People also ask

Which functions can't be overloaded?

2) Member function declarations with the same name and the name parameter-type-list cannot be overloaded if any of them is a static member function declaration.

Why we Cannot overload a function on return type?

The return type of a function has no effect on function overloading, therefore the same function signature with different return type will not be overloaded. Example: if there are two functions: int sum() and float sum(), these two will generate a compile-time error as function overloading is not possible here.

What are the restrictions on overloading a function?

Restrictions on overloadingAny two functions in a set of overloaded functions must have different argument lists. Overloading functions that have argument lists of the same types, based on return type alone, is an error.

Which function can be overloaded?

Function overloading is a feature of object-oriented programming where two or more functions can have the same name but different parameters. When a function name is overloaded with different jobs it is called Function Overloading.


1 Answers

The reason is C++11 13.1/2:

...

  • Member function declarations with the same name and the same parameter-type-list- as well as member function template declarations with the same name, the same parameter-type-list, and the same template parameter lists cannot be overloaded if any of them, but not all, have a ref-qualifier (8.3.5).

    [ Example:

    class Y {
      void h() &;
      void h() const &; // OK
      void h() &&;      // OK, all declarations have a ref-qualifier
    
      void i() &;
      void i() const;   // ill-formed, prior declaration of i
                        // has a ref-qualifier
    };
    

    —end example ]

In ohter words, your example would work if you added a ref-qualifier to the const overload of vals().

like image 132
Angew is no longer proud of SO Avatar answered Sep 18 '22 20:09

Angew is no longer proud of SO