c++ - 家长注册 child 的方法: how to avoid the design anti-patterns?

标签 c++ anti-patterns

struct Base {
  void foo(??? fn) {
    // do something with fn
  }
};

struct A : Base {
  A() : Base() { ... }
  void aa() { ... }
  void aaa() { ... }
};

struct B : Base {
  B() : Base() { ... }
  void bb() { ... }
};

int main() {
  A a, B b;
  a.foo(a.aa); // foo works with aa()
  a.foo(a.aaa); // foo works with aaa()
  b.foo(b.bb); // foo works with bb()
  return 0;
}

我希望fn 成为Base 子类的某个成员函数(返回void,无参数)。这似乎是一个糟糕的设计: parent 不应该知道他们的 child 。但是,将功能写入每个子类会导致代码重复。我想让 children 尽可能瘦。

实现所需功能的最佳设计是什么?

最佳答案

std::function<void()>问好,它执行的任务是抽象任何返回 void 且没有参数的函数。

编辑:为什么不直接使用虚函数呢?喜欢

struct Base {
private:
  virtual void fn() = 0;
public:
  void foo() {
    // do something with fn
  }
};

struct A : Base {
  A() : Base() { ... }
  void fn() { ... }
};

struct B : Base {
  B() : Base() { ... }
  void fn() { ... }
};

int main() {
  A a, B b;
  a.foo(); // foo works with aaa()
  b.foo(); // foo works with bb()
  return 0;
}

不过,确实限制了每个派生类只能使用一个重写函数。

关于c++ - 家长注册 child 的方法: how to avoid the design anti-patterns?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11588466/

相关文章:

c++ - const (c++) 是可选的吗?

c++ - 可能操作错误,随机个位数输出

sql-server - 糟糕的现实世界数据库模式

angularjs - 在 Controller 中使用 Angular 的 $watch 是反模式吗?

C++预期的不合格ID

c++ - 如何编译需要 <winsock2.h> 的 c++ 项目?

c++ - 如何在 C++ 中创建和管理 session ?

anti-patterns - 馄饨代码 - 为什么是反模式?

java - OutOfMemoryError java堆空间

c# - 滥用闭包?违反各种原则?或者好吗?