Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.