Last active
July 1, 2018 23:08
-
-
Save jingzhehu/d12799a90d72fb2c3e5f1c31d385ec2f to your computer and use it in GitHub Desktop.
CRTP: curiously recurring template pattern
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> | |
| template<typename T> | |
| struct inequality { | |
| bool operator!=(const T& that) { | |
| return !(static_cast<const T&>(*this) == that); | |
| } | |
| }; | |
| // mutual dependence of inequality and point | |
| // derived class inherit from a base class templatized with the derived class | |
| // --- it does make my head hurt ! --- | |
| class point : public inequality<point> { | |
| public: | |
| point(int x, int y) : x(x), y(y) {}; | |
| bool operator==(const point& that) const { | |
| return (x == that.x && y == that.y); | |
| }; | |
| private: | |
| int x, y; | |
| }; | |
| int main() { | |
| // CTRP: curiously recurring template pattern | |
| point p1(3, 4), p2(3, 5); | |
| if (p1 != p2) { | |
| std::cout << "pt 1 doesn't equal to pt 2" << std::endl; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment