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/