Skip to content

Instantly share code, notes, and snippets.

@tfc
Last active November 22, 2017 19:14
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tfc/d1d576eb75a1526331e9 to your computer and use it in GitHub Desktop.
Save tfc/d1d576eb75a1526331e9 to your computer and use it in GitHub Desktop.
comparison_impl<T> implementation example code
#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