Skip to content

Instantly share code, notes, and snippets.

@jingzhehu
Last active July 1, 2018 23:08
Show Gist options
  • Select an option

  • Save jingzhehu/d12799a90d72fb2c3e5f1c31d385ec2f to your computer and use it in GitHub Desktop.

Select an option

Save jingzhehu/d12799a90d72fb2c3e5f1c31d385ec2f to your computer and use it in GitHub Desktop.
CRTP: curiously recurring template pattern
#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