Created
January 3, 2014 12:13
-
-
Save fresky/8237006 to your computer and use it in GitHub Desktop.
CRTP vs virtual function example.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
using namespace std; | |
template<typename Derived> class Parent | |
{ | |
public: | |
void SayHi() | |
{ | |
static_cast<Derived*>(this)->SayHiImpl(); | |
} | |
private: | |
void SayHiImpl() | |
{ | |
cout << "hi, i'm default!" << endl; | |
} | |
}; | |
class ChildA :public Parent<ChildA> | |
{ | |
public: | |
void SayHiImpl() | |
{ | |
cout << "hi, i'm child A!" << endl; | |
} | |
}; | |
class ChildB :public Parent<ChildB> | |
{ | |
}; | |
class ParentB | |
{ | |
public: | |
void virtual SayHi() | |
{ | |
cout << "hi, i'm default!" << endl; | |
} | |
}; | |
class ChildC : public ParentB | |
{ | |
public: | |
void SayHi() | |
{ | |
cout << "hi, i'm ChildC!" << endl; | |
} | |
}; | |
class ChildD : public ParentB | |
{ | |
}; | |
template<typename Derived> void CRTP(Parent<Derived>& p) | |
{ | |
p.SayHi(); | |
} | |
void Dynamic(ParentB& p) | |
{ | |
p.SayHi(); | |
} | |
int _tmain(int argc, TCHAR* argv[]) | |
{ | |
ChildA a; | |
CRTP(a); | |
cout << "size of ChildA: " << sizeof(a) << endl; | |
ChildB b; | |
CRTP(b); | |
cout << "size of ChildB: " << sizeof(b) << endl; | |
ChildC c; | |
Dynamic(c); | |
cout << "size of ChildC: " << sizeof(c) << endl; | |
ChildD d; | |
Dynamic(d); | |
cout << "size of ChildD: " << sizeof(d) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment