【发布时间】:2013-12-31 02:46:32
【问题描述】:
这里的钩子函数本身需要检查也属于类层次结构的数据成员的typeid。因此,我为该类层次结构定义了一个模板方法。这是我遇到的烂摊子:
void Person::leave() {
// code
hook(); // private virtual
// code
}
void Girl::hook() { // Girl is a derived class of Person, with data member location
// of type Location which itself has a derived class House
// code
location.locationHook(this);// what happens here depends on what kind of location she is in
// code
}
void Location::locationHook(Person* person) {
// Oh oh! This depends on what class person is
}
void House::locationHook(Person* person) {
// Oh oh! This depends on what class person is
}
所以对于这种情况,我必须求助于我原来的方法,即为每种类型的 Person 派生类使用 typeid(*person) 和 dynamic_cast 和 if 语句来定义虚拟 locationHook,对吗?
【问题讨论】:
-
请添加语言标签(可能是c++)并说明“模板方法”是指“模板方法模式”(可能)还是C++模板。
标签: c++ hook template-method-pattern