Created
July 9, 2015 09:21
-
-
Save ashwin/4f270ccde1e39218b306 to your computer and use it in GitHub Desktop.
Simple C++ code to understand CRTP
This file contains 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> | |
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