Topic: The clone function (Was: Member Template on the type of "this")
Author: Valentin Bonnard <Bonnard.V@wanadoo.fr>
Date: 1999/10/30 Raw View
Claude Qu=E9zel wrote:
>=20
> Valentin Bonnard wrote:
>=20
> > Causing MI of base of we derive further and want
> > to apply the same trick. Even if we add a virtual:
> >
> > template<class T>
> > class BaseImpl : public virtual Base { ... };
> >
> > class Der2 : public Der, BaseImpl<Der2> {};
> >
> > It won't work because there are two overriders
> > for clone (BaseImpl<Der>::clone () and
> > BaseImpl<Der2>::clone ()) and neither one is a
> > final overrider. Here is a possible solution: let's
> > say you wanted this inheritance hierarchy:
> >
> > Base
> > |
> > Derived
> > |
> > Derived2
> >
[ some complicated code ]
> I would like some comments on this way of doing things.
clone is really really a trivial function.
Something is gained by all this stuff only if it is either:
- simplier (no)
- more readable (no)
- less error prone (given the trivial nature of=20
clone, I don't think so)
- more efficient (no)
- has less redondancies (?)
The solution I prefer for clone is:
#define REQUIRED_MEMBERS_CONCRETE_CLASS(class_name) \
protected: \
class_name* do_clone () const \
{ \
return new (*this); \
}
class Base {
protected:
virtual Base* do_clone () const =3D 0;
public:
template <class SomeDerived>
static SomeDerived* clone (const SomeDerived* p)
{ // if static template isn't allowed, then make it friend
SomeDerived* c =3D p->do_clone ();
assert (typeid (*c) =3D=3D typeid (*p));
return c;
}
};
class Derived : public Base {
REQUIRED_MEMBERS_CONCRETE_CLASS(Derived)
};
It is:
- run-time checked
- simple, readable, understandable, not error prone
- has few redondancies
--=20
Valentin Bonnard
---
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@ncar.ucar.edu ]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html ]