namespace
<utility>

std::rel_ops

namespace rel_ops {  template <class T> bool operator!= (const T& x, const T& y);  template <class T> bool operator>  (const T& x, const T& y);  template <class T> bool operator<= (const T& x, const T& y);  template <class T> bool operator>= (const T& x, const T& y);}
Relational Operators
此名稱空間聲明瞭四個關係運算符(!=><=>=)的模板函式,它們的行為分別派生自 operator==(用於 !=)和 operator<(用於 ><=>=)。

1
2
3
4
5
6
namespace rel_ops {
  template <class T> bool operator!= (const T& x, const T& y) { return !(x==y); }
  template <class T> bool operator>  (const T& x, const T& y) { return y<x; }
  template <class T> bool operator<= (const T& x, const T& y) { return !(y<x); }
  template <class T> bool operator>= (const T& x, const T& y) { return !(x<y); }
}

這避免了為每種完整型別宣告所有六個關係運算符的必要性;只需定義兩個:operator==operator<,並匯入此名稱空間,所有六個運算子都將為該型別定義(但如果在匯入時未定義它們,則不會透過依賴於引數的查詢來選擇它們)。

請注意,使用此名稱空間會將這些過載引入到所有未定義自己的過載的型別中。然而,由於非模板函式優先於模板函式,因此對於特定型別,可以透過定義不同的行為來重寫這些運算子中的任何一個。

模板引數

T
對於 operator!=,該型別應為 EqualityComparable
當一個型別支援 operator== 操作並遵循等價關係的典型自反對稱傳遞屬性時,它就是 EqualityComparable

對於 operator>operator<=operator>=,該型別應為 LessThanComparable
當一個型別支援 operator< 操作並定義了有效的嚴格弱序關係時,它就是 LessThanComparable

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// rel_ops example:
#include <iostream>     // std::cout, std::boolalpha
#include <utility>      // std::rel_ops
#include <cmath>        // std::sqrt

class vector2d {
public:
  double x,y;
  vector2d (double px,double py): x(px), y(py) {}
  double length() const {return std::sqrt(x*x+y*y);}
  bool operator==(const vector2d& rhs) const {return length()==rhs.length();}
  bool operator< (const vector2d& rhs) const {return length()< rhs.length();}
};

int main () {
  using namespace std::rel_ops;
  vector2d a (10,10);	// length=14.14
  vector2d b (15,5);	// length=15.81
  std::cout << std::boolalpha;
  std::cout << "(a<b) is " << (a<b) << '\n';
  std::cout << "(a>b) is " << (a>b) << '\n';
  return 0;
}

輸出

(a<b) is true
(a>b) is false


因為我們使用了rel_ops,對於所有定義了operator<(例如vector2d)的型別,也定義了operator>.

資料競爭

引數被傳遞給適當的 operator==operator< 過載,這些過載可以訪問它們。
在任何情況下,這些函式都不能修改其引數(它們是 const 限定的)。

異常安全

如果元素的型別以無異常保證的方式支援相應的操作,則該函式永遠不會丟擲異常(無異常保證)。

另見