我有一个合成图案实现,用于GUI组件:可能性混合复合模式和奇异递归模板模式
class CObject {
private:
CObject * m_pParent;
CObjectContainer * m_pChildren;
void private_foo() {
this->foo();
//Calls private_foo for each child in container.
m_pChildren->foo();
}
public:
virtual void foo() {
//empty for base class
}
virtual CObject * duplicate() {
//Do duplication code
return new CObject(*this);
}
virtual CObject * detach() {
//Remove this object (along with it's children)
//from current tree.
m_pParent->RemoveChild(this);
m_pParent = nullptr;
return this;
}
}
class CSpecificObject : public CObject {
public:
virtual void foo() {
//Specific code for this class
}
virtual CSpecificObject * duplicate() {
//Overload, but the code only calls diferent constructor
return new CSpecificObject(*this);
}
virtual CSpecificObject * detach() {
//Note the code is identical.
m_pParent->RemoveChild(this);
m_pParent = nullptr;
return this;
}
}
不幸的是继承类的数量迅速增加,并且重复的代码(在给定的例子仅detach()方法)让我头疼。
有没有办法干净地实现detach()方法,保持返回类型与它所调用的对象相同?
我在想CRTP,但我不能想办法,以保持动态多态性与编译时多态性沿:
template <Child>
class CObject {
private:
...
Child * detach() {
m_pParent->RemoveChild(this);
m_pParent = nullptr;
return static_cast<Child*>(this);
}
...
}
//Array of CObject* pointers is no longer possible.
'分离()'方法用于在丑陋的方式: 'CObject的* tree_of_stuff;' - 对象的完整树 'CSpecificObject * specific_object = tree_of_stuff->子( “的StringID”) - > detach();' 这里'Child <>()'方法沿着树进行搜索并将对象转换为指定的模板参数。如果'detach()'返回'void'或'CObject *',则此语法不可用。 –
'duplicate()'方法是一定的错误来源,这是我用CRTP扩展当前模式的原因之一。在我看来,依靠复制构造函数是更安全的,承诺每个人都会实现'duplicate()'方法。 –