我可以看到像下面这样有用的东西:
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/