Skip to content

Instantly share code, notes, and snippets.

@ashwin
Created July 9, 2015 09:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ashwin/4f270ccde1e39218b306 to your computer and use it in GitHub Desktop.
Save ashwin/4f270ccde1e39218b306 to your computer and use it in GitHub Desktop.
Simple C++ code to understand CRTP
#include <iostream>
using namespace std;
template <typename Derived>
struct Creature
{
int eye_num;
friend bool operator == (const Derived& lhs, const Derived& rhs)
{
return lhs.IsEqual(rhs);
}
friend bool operator != (const Derived& lhs, const Derived& rhs)
{
return !(lhs.IsEqual(rhs));
}
};
struct Bird: Creature<Bird>
{
int wing_num;
bool IsEqual(const Bird& b) const
{
return eye_num == b.eye_num && wing_num == b.wing_num;
}
};
struct Fish: Creature<Fish>
{
int fin_num;
bool IsEqual(const Fish& f) const
{
return eye_num == f.eye_num && fin_num == f.fin_num;
}
};
int main()
{
Bird b1, b2, b3;
b1.eye_num = 2;
b2.eye_num = 2;
b3.eye_num = 2;
b1.wing_num = 2;
b2.wing_num = 2;
b3.wing_num = 3;
if (b1 != b2) cout << "Bird equal\n";
else cout << "Bird not equal\n";
if (b1 == b3) cout << "Bird equal\n";
else cout << "Bird not equal\n";
// You can do the same with Fish:
// Fish f1, f2, f3;
// f1.fin_num = 5;
// and so on ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment