namespace std {
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 );
}}
この機能は、C++20から非推奨となった。代わりに一貫比較機能を使用すること。
概要
std::rel_ops名前空間は、関係演算子を自動的に定義する。
operator!=()は、operator==()によって定義され、operator>()、operator<=()、operator>=()は、operator<()によって定義される。
各演算子の定義は以下の通りである:
namespace std {
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!=()に対し、型TはEqualityComparableである必要がある。
すなわち、型Tはoperator==()による比較が可能であり、その比較は反射律、対象律、推移律を満たさねばならない。
operator>()、operator<=()、operator>=()に対し、型TはLessThanComparableである必要がある。
すなわち、型Tはoperator<()による比較が可能であり、その比較は狭義の弱順序でなければならない。
非推奨の詳細
C++20で一貫比較演算子が追加された。この機能によって比較演算子を容易に定義できるようになったため、比較演算子の簡潔な定義をサポートする本機能は不要になった。
例
#include <utility>
struct X {
int value;
};
bool operator==(const X& a, const X& b)
{
return a.value == b.value;
}
bool operator<(const X& a, const X& b)
{
return a.value < b.value;
}
// operator==()、operator<()以外は自動定義
bool operator!=(const X& a, const X& b)
{
return std::rel_ops::operator!=(a, b);
}
bool operator>(const X& a, const X& b)
{
return std::rel_ops::operator>(a, b);
}
bool operator<=(const X& a, const X& b)
{
return std::rel_ops::operator<=(a, b);
}
bool operator>=(const X& a, const X& b)
{
return std::rel_ops::operator>=(a, b);
}
int main()
{
const X a = {1};
const X b = {1};
const X c = {2};
if (a == b) {}
if (a != b) {}
if (a < c) {}
if (a <= c) {}
if (a > c) {}
if (a >= c) {}
}
出力
参照
- このライブラリを使う場合、 Boost Operators Libraryの使用も検討すべきである。
- P0768R1 Library Support for the Spaceship (Comparison) Operator