如何使用 Pimpl 授予 public 成员访问权限?

How to give access to public members with Pimpl?

#include <memory>

class MyClassImpl;

class MyClass {
    void Foo();

    struct MyStruct {
      int a;
      int b;
    } variable_struct;
private:
    std::unique_ptr<MyClassImpl> m_pImpl;
};
class MyClassImpl
{
public:
    void DoStuff() { /*...*/ }
    struct MyStructImpl {
      int a;
      int b;
    } variable_struct_impl;
};


// MyClass (External/User interface)
MyClass::MyClass () : m_pImpl(new MyClassImpl()) { }

MyClass::~MyClass () = default;

void MyClass::Foo() {
    m_pImpl->DoStuff();
}

对于methods,说的很清楚了,反正我们还是要做forward方法。 (示例中 Foo() 转发到 DoStuff()

How to give access to public members with Pimpl?

你不知道。 PIMPL 的要点是隐藏 Private IMPLementation 的所有成员,public 访问它们完全违背了这一点。

如果您想要公开访问,请不要将成员放入 PIMPL。