静态多态(模版模拟多态)

虚函数的使用会带来额外的开销,具有虚函数的class类型都需要一张虚函数表,而每多一个虚函数,对应类型的对象的大小就会增加4bytes(32位机器下),夸张的试想一下如果有10个父类,每个父类都有100个虚函数的情况下,每个对象会增加多少?
4x10x100=4000bytes!
除了空间上的开销,每个虚函数的调用在时间上都会比普通函数多一次整形加法和一次指针间接引用,也就是时间上的开销。
 
template<typename Derived>
class Basic
{
public:
       inline void Print() {
            SelfCast()->Print();
      }

protected:
       inline Derived* SelfCast() {
             return static_cast <Derived*>(this);
      }
};
class Derived1 : public Basic<Derived1>
{
public:
      Derived1() {}

      inline void Print() {
            std::cout << "Derived1 Print" << std::endl;
      }
};
class Derived2 : public Basic<Derived2>
{
public :
      Derived2() {}

       inline void Print() {
            std::cout << "Derived2 Print" << std::endl;
      }

       static std::string Name() {
             return "Derived2 Class" ;
      }
};

调用方法:、
Basic<Derived1>* der1 = new Derived1();
der1->Print();
Basic<Derived2>* der2 = new Derived2();
der2->Print();

输出结果:
Derived1 Print
Derived2 Print

这里实现的关键是SelfCast函数,通过static_cast把当前对象强制转换为具体指定的子类对象,这里是Derived1。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值