Last active
November 22, 2017 19:14
-
-
Save tfc/d1d576eb75a1526331e9 to your computer and use it in GitHub Desktop.
comparison_impl<T> implementation example code
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 <assert.h> | |
template <typename T> | |
class comparison_impl | |
{ | |
const T& thisT() const { return *static_cast<const T*>(this); } | |
public: | |
// operator== is implemented by T | |
template <typename U> | |
bool operator!=(const U& o) const { return !(thisT() == o); } | |
// operator< is implemented by T | |
template <typename U> | |
bool operator>=(const U& o) const { return !(thisT() < o); } | |
// operator> is implemented by T | |
template <typename U> | |
bool operator<=(const U& o) const { return !(thisT() > o); } | |
}; | |
template <typename U, typename T> | |
typename std::enable_if<!std::is_same<U, T>::value, bool>::type | |
operator==(const U &lhs, const comparison_impl<T> &rhs) | |
{ | |
return static_cast<const T&>(rhs) == lhs; | |
} | |
template <typename U, typename T> | |
typename std::enable_if<!std::is_same<U, T>::value, bool>::type | |
operator!=(const U &lhs, const comparison_impl<T> &rhs) | |
{ | |
return !(static_cast<const T&>(rhs) == lhs); | |
} | |
class Foo : public comparison_impl<Foo> | |
{ | |
int x; | |
public: | |
explicit Foo(int x_) : x{x_} {} | |
bool operator==(const Foo &o) const { return x == o.x; } | |
bool operator==(int o) const { return x == o; } | |
}; | |
int main() | |
{ | |
assert(Foo{0} == 0); | |
assert(Foo{0} != 1); | |
assert(Foo{0} == Foo{0}); | |
assert(Foo{0} != Foo{1}); | |
assert(0 == Foo{0}); | |
assert(0 != Foo{1}); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment