If I have a type that consists of a single numeric data member (say, an int) and various methods, is there a convenient way to tell the compiler to automaticall
The C++ way of doing this is to use a tag type and ADL. Here is a quick example:
namespace relational {
struct tag {};
template
bool operator== (T const& lhs, T const& rhs) { return !(rhs < lhs) && !(lhs < rhs); }
template
bool operator!= (T const& lhs, T const& rhs) { return !(lhs == rhs); }
template
bool operator> (T const& lhs, T const& rhs) { return rhs < lhs; }
template
bool operator<= (T const& lhs, T const& rhs) { return !(rhs < lhs); }
template
bool operator>= (T const& lhs, T const& rhs) { return !(lhs < rhs); }
}
struct foo: relational::tag {
int value;
foo(int value): value(value) {}
bool operator< (foo const& other) const { return this->value < other.value; }
};
#include
void compare(foo f0, foo f1) {
std::cout << std::boolalpha
<< f0.value << " == " << f1.value << " => " << (f0 == f1) << '\n'
<< f0.value << " != " << f1.value << " => " << (f0 != f1) << '\n'
<< f0.value << " < " << f1.value << " => " << (f0 < f1) << '\n'
<< f0.value << " <= " << f1.value << " => " << (f0 <= f1) << '\n'
<< f0.value << " > " << f1.value << " => " << (f0 > f1) << '\n'
<< f0.value << " >= " << f1.value << " => " << (f0 >= f1) << '\n'
;
}
int main() {
compare(foo(1), foo(2));
compare(foo(2), foo(2));
}