std::rel_ops::operator!=,>,<=,>=
From cppreference.com
| ヘッダ <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) operator!=
|
|---|
namespace rel_ops { template<class T> bool operator!=(const T& lhs, const T& rhs) { return !(lhs == rhs); } } |
(2) operator>
|
namespace rel_ops { template<class T> bool operator>(const T& lhs, const T& rhs) { return rhs < lhs; } } |
(3) operator<=
|
namespace rel_ops { template<class T> bool operator<=(const T& lhs, const T& rhs) { return !(rhs < lhs); } } |
(4) operator>=
|
namespace rel_ops { template<class T> bool operator>=(const T& lhs, const T& rhs) { return !(lhs < rhs); } } |
[編集] 注釈
Boost.operators は、std::rel_ops よりも汎用性の高い代替手段を提供します。
C++20 の時点では、std::rel_ops は operator<=> に置き換えられ、非推奨となっています。
[編集] 例
このコードを実行
#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 << "{1} != {2} : " << (f1 != f2) << '\n' << "{1} > {2} : " << (f1 > f2) << '\n' << "{1} <= {2} : " << (f1 <= f2) << '\n' << "{1} >= {2} : " << (f1 >= f2) << '\n'; }
出力
{1} != {2} : true
{1} > {2} : false
{1} <= {2} : true
{1} >= {2} : false