Re: cloning struct and derived structs with primitive type members
If it's OK for you to change each derived class declaration from
struct derivedXXX : public params
to
struct derivedXXX : public clonable_params<derivedXXX>
Then you won't have to define clone() for every class. Just once in the
base class.
I.e.
struct params
{
protected:
virtual params * do_clone() const =0;
public:
params * clone() const
{
return do_clone();
}
//
};
template <typename T>
struct clonable_params : public params
{
T * do_clone() const
{
return new T(*static_cast<T*>(this));
}
};
The problem that I see with your solution is that it is limited to one
step hierarchies and that the cloning method overriding lacks covariance.
There is actually no way to make a solutions based on inheriting from
the "auto-clone" class that can respect covariance because in that case
the "auto-clone"d type is incomplete in the context of the clone()
function definition and therefore the compiler complains about covariance.
As an example:
template <class T, class Next = void>
struct copy_cloneable : public Next
{
virtual T* clone() { return new T (*static_cast<T*>(this)); }
virtual ~copy_cloneable () {}
};
template <class T>
struct copy_cloneable<T, void>
{
virtual T* clone() { return new T (*static_cast<T*>(this)); }
virtual ~copy_cloneable () {}
};
struct A : public copy_cloneable<A> {};
struct B : public copy_cloneable<B, A> {};
Yields:
test.cpp: In instantiation of 'copy_cloneable<B, A>':
test.cpp:19: instantiated from here
test.cpp:7: error: invalid covariant return type for 'T*
copy_cloneable<T, Next>::clone() [with T = B, Next = A]'
test.cpp:14: error: overriding 'T* copy_cloneable<T, void>::clone()
[with T = A]'
With GCC.
(Yeah, actually I built the code thinking that it was a good solution
just to realize about this partial definition problem, it's too late in
my time zone :p)
JP
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]