문제

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.

도움이 되었습니까?

해결책

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

다른 팁

Read about std::rel_ops. Nobody uses it.

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top