通过私有继承覆盖公共别名方法

Cur*_*ous 0 c++ polymorphism inheritance private-inheritance c++17

我有一个类层次结构,其中有一个Base带有实现列表的基类型和另一个基类,AnotherBase几乎相同,Base但略有不同。为了用语言表达这一点,我在第二个基类上使用了私有继承(因此后者与前者的实现之间没有原样的关系)。

假设这是代码(https://wandbox.org/permlink/2e2EG0eKmcLiyvgt

#include <iostream>

using std::cout;
using std::endl;

class Base {
public:
    virtual ~Base() = default;
    virtual void foo() = 0;
};

class Impl : public Base {
public:
    void foo() {
        cout << "Impl::foo()" << endl;
    }
};

class AnotherBase : private Base {
public:
    using Base::foo;

    // other virtual methods
};

class Derived : public AnotherBase {
public:
    explicit Derived(std::unique_ptr<Base> base) : base_{std::move(base)} {}

    void foo() override {
        base_->foo();
    }

private:
    std::unique_ptr<Base> base_;
};

int main() {
    auto impl = std::make_unique<Impl>();
    std::make_unique<Derived>(std::move(impl))->foo();
}
Run Code Online (Sandbox Code Playgroud)

当我尝试编译上述代码时,出现以下错误

prog.cc:27:38: error: 'Base' is a private member of 'Base'
Run Code Online (Sandbox Code Playgroud)

如果这不起作用,表达上述想法的最佳方式是什么?还有为什么它不起作用?

cdh*_*wie 5

在 , 声明中的这两行中DerivedBase被解析为私有继承Base类型,因为它在范围内——即使它是私有的:

explicit Derived(std::unique_ptr<Base> base) : base_{std::move(base)} {}
// ...
std::unique_ptr<Base> base_;
Run Code Online (Sandbox Code Playgroud)

C++ 不会忽略引用当前作用域无法访问的事物的作用域内名称。编译器会在外部范围内查找Base确实有权访问的a 似乎是合乎逻辑的,但这不是发生的情况。编译器只是在Base它看到的最近的地方停止,而不考虑任何访问修饰符。

这可以Base通过顶级命名空间前缀引用类型来轻松修复::

explicit Derived(std::unique_ptr<::Base> base) : base_{std::move(base)} {}
// ...
std::unique_ptr<::Base> base_;
Run Code Online (Sandbox Code Playgroud)

两者都引用相同的类型,但Derived不能访问继承的Base名称,而可以访问全局Base名称。

您还可以通过重新定义解决这个问题Base中表示Derived。在Derived声明的顶部,您可以添加:

protected:
    using Base = ::Base;
Run Code Online (Sandbox Code Playgroud)

这将继承的Base名称隐藏在Derived有权访问的类型别名后面。