C++ 多态Clone方法的模板化实现方式笔记

本文介绍了C++中的Cloneable模板如何用于创建派生类的克隆方法,以及C++11后通过unique_ptr改进实现的方式,重点提及了CuriouslyRecurringTemplatePattern(CRTP)的概念和应用实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

直接上模板工具类:

template <typename Base, typename Derived>
class Cloneable : public Base
{
public:
    using Base::Base;
 
    virtual Base *clone() const
    {
        return new Derived(static_cast<Derived const &>(*this));
    }
};

使用方法示例:
基类Vehicle

class Vehicle
{
protected:
    int fuelCapacity;
 
public:
    Vehicle() {};
    Vehicle(int fuelCapacity) : fuelCapacity(fuelCapacity) {};
    virtual ~Vehicle() {};
    virtual Vehicle *clone() const = 0;
 
    virtual void describe() const = 0;
};

一级子类Plane,使用了Cloneable模板生成了clone方法:

class Plane : public Cloneable<Vehicle, Plane>
{
private:
	typedef Cloneable<Vehicle, Plane> BaseClass;
 
protected:
	int wingSpan;
 
public:
	Plane() {};
	Plane(int fuelCapacity, int wingSpan) : BaseClass(fuelCapacity), wingSpan(wingSpan) {};
 
	virtual void describe() const
	{
 		std::cout << "I am a plane" << std::endl;
	}
};

二级子类FighterPlane,同样也能使用Cloneable模板生成clone方法:

class FighterPlane : public Cloneable<Plane, FighterPlane>
{
private:
	typedef Cloneable<Plane, FighterPlane> BaseClass;
 
protected:
	int numberOfBombs;
 
public:
	FighterPlane() {};
	FighterPlane(int fuelCapacity, int wingSpan, int numberOfBombs)
 	: BaseClass(fuelCapacity, wingSpan), numberOfBombs(numberOfBombs) {};
 
	virtual void describe() const
	{
		std::cout << "I am a fighter plane" << std::endl;
	}
};

clone方法在C++11后更好的实现方式是返回unique_ptr,例子为了简化使用了原始指针方式表示。

参考:
C++: Polymorphic cloning and the CRTP (Curiously Recurring Template Pattern)
参考内含有详细的解释。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值