Note that there are some explanatory texts on larger screens.

plurals
  1. POPossibility to mix composite pattern and curiously recurring template pattern
    primarykey
    data
    text
    <p>I have a composite pattern implementation, used for GUI components:</p> <pre><code>class CObject { private: CObject * m_pParent; CObjectContainer * m_pChildren; void private_foo() { this-&gt;foo(); //Calls private_foo for each child in container. m_pChildren-&gt;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-&gt;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-&gt;RemoveChild(this); m_pParent = nullptr; return this; } } </code></pre> <p>Unfortunately the number of inherited classes increases rapidly and the duplicate code (in given example only the detach() method) is giving me a headache.</p> <p>Is there a way to cleanly implement detach() methods, keeping the return type the same as the object, on which it is called?</p> <p>I was thinking about CRTP, but I can not think of a way to keep the dynamic polymorphism along with compile time polymorphism:</p> <pre><code>template &lt;Child&gt; class CObject { private: ... Child * detach() { m_pParent-&gt;RemoveChild(this); m_pParent = nullptr; return static_cast&lt;Child*&gt;(this); } ... } //Array of CObject* pointers is no longer possible. </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload