Pregunta

Today I was implementing a datatype, in which I decided to overload the comparison operators. While doing this, a question popped into my head.

Why do I, as a programmer, have to define every single comparison operator, when all I do, is to define them in terms of '<' (see below)? - That is, why doesn't the compiler automatically generate these for me.

a == b    =>    !(a<b || b<a)
a != b    =>     (a<b || b<a)
a > b     =>    b < a
a >= b    =>    !(a < b)
a <= b    =>    !(b < a)

I do understand, that it is perfectly reasonable for performance reasons, to want to implement more than just '<'.

I know the obvious answer is, that it's because I can easily do it myself, but I do believe that compilers/language specifications should do whatever possible to ease using the language.

¿Fue útil?

Solución

Define operator<() and operator==(), and

#include <utility>
using namespace std::rel_ops;

Then all comparison operators are automatically defined. See the example provided by cppreference.com

Otros consejos

Read about std::rel_ops. Nobody uses it.

You can use boost::operators. It does exactly what you want and much more.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top