使用 PrivateOps 来隐藏私有函数

#51 · open · 0 comments

View on GitHub ↗

chen3feng

# 方法1 In header file: ```cpp class Foo { public: void Method(); private: class Impl; Impl* AsImpl(); std::aligned_storage<64, 8> storage_; }; ``` In cpp file: ```cpp class Foo::Impl { public: int x; int y; string s; }; static_assert(sizeof(Foo) == sizeof(Foo::Impl)); static_assert(aligof(Foo) == aligof(Foo::Impl)); Foo::Impl* Foo::AsImpl() { return reinterrept_cast<Foo::Impl*>(&storage_); } void Foo::Method() { Impl* impl = AsImpl(); impl->...; } ``` # 方法2 In header file: ```cpp class Foo { public: int GetX() const { return x; } int GetY() const { return y; } private: int x; int y; friend class PrivateOps; } ``` In cpp file: ```cpp class Foo::PrivateOps { public: static void Method1(Foo* self); static void Method2(Foo* self); }; ```

Comments