Derived curiously recurring templates and covariance

前端 未结 2 1169
野的像风
野的像风 2021-01-04 20:35

Suppose I have a base class which cloning of derived classes:

class Base
{
    public:
        virtual Base * clone()
        {
            return new Base()         


        
2条回答
  •  失恋的感觉
    2021-01-04 21:01

    A not-so-pretty workaround.

    class Base
    {
        protected:
            virtual Base * clone_p()
            {
                return new Base();
            }
    };
    
    
    template 
    class CRTP : public Base
    {
        protected:
            virtual CRTP* clone_p()
            {
                return new T;
            }
        public:
            T* clone()
            {
                CRTP* res = clone_p();
                return static_cast(res);
            }
    };
    
    
    class Derived : public CRTP
    {
        public:
    };
    

    Use dynamic_cast<> instead of static if you feel it's safer.

提交回复
热议问题