chen3feng / article

本人的文章和笔记,充当懒人 Blog 来用。
9 stars 1 forks source link

使用 PrivateOps 来隐藏私有函数 #51

Open chen3feng opened 9 months ago

chen3feng commented 9 months ago

方法1

In header file:

class Foo {
public:
  void Method();
private:
  class Impl;
  Impl* AsImpl();
  std::aligned_storage<64, 8> storage_;
};

In cpp file:

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:

class Foo {
public:
  int GetX() const { return x; }
  int GetY() const { return y; }
private:
  int x;
  int y;
  friend class PrivateOps;
}

In cpp file:

class Foo::PrivateOps {
public:
  void Method1(Foo* foo);
  void Method2(Foo* foo);
};