Skip to content

Instantly share code, notes, and snippets.

@fresky
Created January 3, 2014 12:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fresky/8237006 to your computer and use it in GitHub Desktop.
Save fresky/8237006 to your computer and use it in GitHub Desktop.
CRTP vs virtual function example.
#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