【C++模版之旅】靜態多態(模版類比多態)的討論

來源:互聯網
上載者:User

#include <iostream>#include <string>class BasicClassic{public:       virtual void Print() = 0;};class DerivedClassic1 : public BasicClassic{public:      DerivedClassic1() {}       virtual void Print() {            std::cout << "DerivedClassic1 Print" << std::endl;      }};class DerivedClassic2 : public BasicClassic{public:      DerivedClassic2() {}       virtual void Print() {            std::cout << "DerivedClassic2 Print" << std::endl;      }};
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 PrintDerived2 Print具有虛函數的class類型都需要一張虛函數表,而每多一個虛函數,對應類型的對象的大小就會增加4bytes(32位機器下),誇張的試想一下如果有10個父類,每個父類都有100個虛函數的情況下,每個對象會增加多少?每個虛函數的調用在時間上都會比普通函數多一次整形加法和一次指標間接引用,也就是時間上的開銷。
template <typename Derived>class Basic{public :      Basic() {  }       inline void Print() {            std::cout << Basic<Derived>::Name() << std::endl;            SelfCast()->Print();      }       static std::string Name() {             return Derived::Name();      }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;      }       static std::string Name() {             return "Derived1 Class" ;      }};


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.