std::rel_ops::operator!=,>,<=,>=
提供: cppreference.com
<tbody>
</tbody>
| ヘッダ <utility> で定義
|
||
template< class T > bool operator!=( const T& lhs, const T& rhs ); |
(1) | (C++20で非推奨) |
template< class T > bool operator>( const T& lhs, const T& rhs ); |
(2) | (C++20で非推奨) |
template< class T > bool operator<=( const T& lhs, const T& rhs ); |
(3) | (C++20で非推奨) |
template< class T > bool operator>=( const T& lhs, const T& rhs ); |
(4) | (C++20で非推奨) |
T 型のオブジェクト対するユーザ定義の operator== および operator< を元に、他の比較演算子の通常の意味論を実装します。
1) operator== を用いて operator!= を実装します。
2) operator< を用いて operator> を実装します。
3) operator< を用いて operator<= を実装します。
4) operator< 用いて operator>= を実装します。
引数
| lhs | - | 左側の引数 |
| rhs | - | 右側の引数 |
戻り値
1) lhs が rhs と等しくない場合、 true を返します。
2) lhs が rhs より大きい場合、 true を返します。
3) lhs が rhs より小さいまたは等しい場合、 true を返します。
4) lhs が rhs より大きいまたは等しい場合、 true を返します。
実装例
| 1つめのバージョン |
|---|
namespace rel_ops {
template< class T >
bool operator!=( const T& lhs, const T& rhs )
{
return !(lhs == rhs);
}
}
|
| 2つめのバージョン |
namespace rel_ops {
template< class T >
bool operator>( const T& lhs, const T& rhs )
{
return rhs < lhs;
}
}
|
| 3つめのバージョン |
namespace rel_ops {
template< class T >
bool operator<=( const T& lhs, const T& rhs )
{
return !(rhs < lhs);
}
}
|
| 4つめのバージョン |
namespace rel_ops {
template< class T >
bool operator>=( const T& lhs, const T& rhs )
{
return !(lhs < rhs);
}
}
|
ノート
boost.operators はさらに多様な std::rel_ops の代替を提供します。
C++20 以降、 operator<=> が導入されたため、 std::rel_ops は非推奨になりました。
例
Run this code
#include <iostream>
#include <utility>
struct Foo {
int n;
};
bool operator==(const Foo& lhs, const Foo& rhs)
{
return lhs.n == rhs.n;
}
bool operator<(const Foo& lhs, const Foo& rhs)
{
return lhs.n < rhs.n;
}
int main()
{
Foo f1 = {1};
Foo f2 = {2};
using namespace std::rel_ops;
std::cout << std::boolalpha;
std::cout << "not equal? : " << (f1 != f2) << '\n';
std::cout << "greater? : " << (f1 > f2) << '\n';
std::cout << "less equal? : " << (f1 <= f2) << '\n';
std::cout << "greater equal? : " << (f1 >= f2) << '\n';
}
出力:
not equal? : true
greater? : false
less equal? : true
greater equal? : false