c++ - Invalid covariant type with CRTP clonable class -
i'm trying implement clonable class crtp. however, need have abstract class have pure virtual clone method, overridden child classes. make happen, need clone function return covariant return type. made code below, , compiler shout @ me error:
main.cpp:12:5: error: return type of virtual function 'clone' not covariant return type of function overrides ('b *' not derived 'abstractclonable *')
the class 'b' seems child class of abstractclonable, , 2 way! how can solve this? thank much. tried both clang 3.6 , gcc 4.9.2
struct abstractclonable { virtual abstractclonable* clone() const = 0; }; template<typename t> struct clonable : virtual abstractclonable { t* clone() const override { return new t{*dynamic_cast<const t*>(this)}; } }; struct : virtual abstractclonable { }; struct b : a, clonable<b> { };
even if b
indeed derived clonable<b>
, problem here clonable<b>
construction not valid, defines
b* clone() const override
which of course not override of abstractclonable::clone()
, since compiler doesn't see b
@ point child of abstractclonable
. believe issue lays in fact compiler cannot build clonable<b>
base of b
.
a workaround (but not same want) define
clonable* clone() const override
in clonable
. mentioned in comment, can define free function
template<typename t> t* clone(const t* object) { return static_cast<t*>(object->clone()); }
Comments
Post a Comment