Re: C++ language: Cloneable classes
On 7 Mai, 19:43, Krzysztof Czainski <1czaj...@gmail.com> wrote:
On 7 Maj, 02:43, Daniel Kr?gler <daniel.krueg...@googlemail.com>
wrote:
"If the return type of D::f differs from the return type of
B::f, the class type in the return type of D::f shall be
complete at the point of declaration of D::f or shall be the
class type D."
In your example, Derived is incomplete at this point and
different from Cloneable.
I see. This explains everything, thanks. So I need a workaround..
#include <memory>
class CloneableBase
{
public:
virtual ~CloneableBase() {}
protected:
virtual CloneableBase* doClone() const = 0;
};
template < typename Derived>
class Cloneable : public CloneableBase
{
public:
typedef std::auto_ptr<Derived> AutoPtr;
AutoPtr clone() const {
return AutoPtr( static_cast<Derived*>(this->doClone()) );
}
};
Yes, I implemented a similar solution in my code, but until now, I
considered it a temporary workaround.. I now see, that it's the final
solution, thanks.
IMO my proposed code could be slightly improved
to come even nearer to your original trial. Essentially
the fix needs only to be done in *Cloneable*, were we
take advantage of the maximum which the standard
allows, i.e. we reintroduce the private doClone() in
the CloneableBase and in Cloneable, whereby we use
Cloneable as the most derived type. The static_cast
remains, but we prevent a subset of previously
allowed misusages:
template < typename Derived >
class Cloneable : public CloneableBase
{
public:
typedef std::auto_ptr<Derived> AutoPtr;
AutoPtr clone() const { return AutoPtr(
static_cast<Derived*>(doClone()) ); }
private:
virtual Cloneable* doClone() const = 0;
};
Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]