#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" ; }};