If I understand you correctly, the problem you are trying to solve is that you have a base class function that needs to know the most derived type of the object so you can copy it. The clone pattern is effectively the only solution. The bad news is you have little choice but to write the method. The good news is that the method is trivial to write.
Templates I don't think will work here because template and virtual don't mix -- you can't write a virtual template function.
Having said all that, boost may have solved this problem using complex template metaprogramming techniques; I'm not sure. If you want, you can research at www.boost.org, however my general impression is that even if they did solve the problem, it will be less time consuming for you to write the clone method for a bunch of objects than to try to integrate the metaprogramming solution.
And having said all that, you could fall back on a "ritualistic" solution by using CRTP (curiously recurring template pattern). The solution would work like this:
1 2 3 4 5 6 7 8 9 10
|
template< typename T >
class clonable {
public:
virtual T* clone() const
{ return new T( dynamic_cast< const T&>( *this ) ); }
};
class derived : public clonable<derived> {
// ...
};
|
The limitations of this approach are:
1) If D is a class derived from clonable, then you cannot write a class D2 which is
derived from D and clonable.
2) The clone() method does not handle exceptions.
3) I'm not sure that this handles volatile either.