Invalid covariant type with CRTP clonable class

前端 未结 3 1943
眼角桃花
眼角桃花 2020-12-20 19:27

I\'m trying to implement a Clonable class with the CRTP. However, I need to have abstract class that have a pure virtual clone method, overridden by child classes. To make t

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-20 20:16

    Even if B is indeed derived from Clonable, the problem here is that Clonable construction is not valid, as it defines

    B* clone() const override
    

    which of course is not an override of AbstractClonable::clone(), since the compiler doesn't see B at this point as a child of AbstractClonable. So I believe the issue lays in the fact that the compiler cannot build the Clonable base of B.

    A workaround (but not really the same as what you want) is to define

    Clonable* clone() const override
    

    in Clonable. As you mentioned in the comment, you can also define a free function

    template 
    T* clone(const T* object) 
    { 
        return static_cast(object->clone()); 
    }
    

    Related: Derived curiously recurring templates and covariance

提交回复
热议问题