为什么 RHR 函数不能重载?

Why can't RHR functions be overloaded?

我发现类似以下的内容很有用:

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

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

但是我在使用 g++ 时遇到编译器错误:

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

我认为您可以使用 const 函数进行相同类型的重载。这对上述访问器用处不大,对运算符更有用。

原因是 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 ]

换句话说,如果您将 ref-qualifier 添加到 vals().

const 重载中,您的示例将起作用