在 C++ 中使用带有 ref 限定符的子成员函数重载不带 ref 限定符的父成员函数

Overloading a parent member function without ref-qualifier with a child member function with ref-qualifier in C++

在 C++ 中,不能在一个 class 中重载带有引用限定符的成员函数和不带引用限定符的成员函数。但同时可以从父 class 继承一个成员函数并在子 class 中重载它,如示例所示:

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
}

仅在调用 f 期间,Clang 抱怨 call to member function 'f' is ambiguous。但是GCC接受程序没有任何错误,demo: https://gcc.godbolt.org/z/5zzbWcs97

这里是哪个编译器?

GCC 正确 接受这一点,但最近情况发生了变化。当前的措辞是 class 中的 using-declaration 忽略 (base-class) 不明确的声明(在某种意义上比用于重载决议,部分原因是还没有参数列表)和 class 中的其他声明。 void()void() & 成员在这个意义上是不明确的,所以 b.f 只找到 Bf 并且调用有效。

在标准的先前(截至撰写本文时,这意味着“已发布”)版本中,这两个函数都可用,因为 & 区分了它们(在某种意义上甚至更严格),这不仅会导致调用模棱两可(如 Clang 所说),而且会完全格式错误,因为已检查 base- 和 derived-class 函数的 overload 兼容性,而它们缺乏这种兼容性。