您的位置:首页 > 其它

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

2014-09-30 09:37 148 查看
虚函数的使用会带来额外的开销,具有虚函数的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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: