2

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.

4

3 回答 3

3

阅读有关std::rel_ops. 没有人使用它。

于 2013-09-05T13:53:05.150 回答
3

定义operator<()operator==(), 和

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

然后自动定义所有比较运算符。请参阅cppreference.com提供的示例

于 2013-09-05T13:53:32.997 回答
2

您可以使用boost::operators。它完全符合您的要求,甚至更多。

于 2013-09-05T14:33:45.260 回答