显然,不允许在ref-qualifiers上重载 - 如果删除&或者&&(只是标记,而不是它们的函数),这段代码将无法编译:
#include <iostream>
struct S {
void f() & { std::cout << "Lvalue" << std::endl; }
void f() && { std::cout << "Rvalue" << std::endl; }
};
int main()
{
S s;
s.f(); // prints "Lvalue"
S().f(); // prints "Rvalue"
}
Run Code Online (Sandbox Code Playgroud)
换句话说,如果您有两个具有相同名称和类型的函数,则必须定义两者,如果您定义其中任何一个.我认为这是故意的,但是原因是什么?例如,为什么不允许调用&&rvalues 的版本(如果已定义),以及f()以下变体中的其他所有内容的"primary" (反之亦然 - 尽管这会让人感到困惑):
struct S {
void f() { std::cout << "Lvalue" << std::endl; }
void f() && { std::cout << "Rvalue" …Run Code Online (Sandbox Code Playgroud) 在 C++ 中,不能在一个类中用没有 ref-qualifier 的成员函数重载带有 ref-qualifier 的成员函数。但同时可以从父类继承一个成员函数并在子类中重载它,如示例所示:
struct A {
void f() {}
//void f() & {} //overload error everywhere
};
struct B : A {
using A::f;
void f() & {} //ok everywhere
};
int main() {
B b;
b.f(); //ok in GCC only
}
Run Code Online (Sandbox Code Playgroud)
只是在调用的过程中f,Clang抱怨道call to member function 'f' is ambiguous。但GCC接受程序没有任何错误,演示: https: //gcc.godbolt.org/z/5zzbWcs97
这里是哪个编译器?
c++ overloading language-lawyer ref-qualifier function-qualifier