c++ - 为什么 RHR 函数不能重载?

标签 c++ c++11

我可以看到像下面这样有用的东西:

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 重载中,您的示例将起作用。

关于c++ - 为什么 RHR 函数不能重载?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27781485/

相关文章:

c++ - 奇怪的编译器行为

c++ - 如何返回节点中的数据?

c++ - C++11 中的线程不在类成员中

Android Studio 14 原生开发 + CrystaX NDK

c++ - 如何从二进制文件中读取bitN整数数据?

c++ - 无法在 lambda 中捕获

c++ - 编译包含 LLVM API header 的 C++ 文件时出错

c++ - 如何创建优化的图形多色记录器?

C++11统一初始化和函数重载

c++ - 获取两天之间的交易日数