std::compare_3way
提供: cppreference.com
| ヘッダ <algorithm> で定義
|
||
| template< class T, class U > constexpr auto compare_3way( const T& a, const U& b ); |
(C++20以上) | |
三方比較を使用して2つの値を比較し、適用可能な最も強い比較カテゴリ型の結果を生成します。
詳細は以下の通りです。
- 式 a <=> b が well-formed であれば、その結果を返します。
- そうでなく、式 a == b および a < b がどちらも well-formed であって、 bool に変換可能であれば、
- a == b が true と等しければ、 std::strong_ordering::equal を返します。
- そうでなく、 a < b が true と等しければ、 std::strong_ordering::less を返します。
- そうでなければ、 std::strong_ordering::greater を返します。
- そうでなく、式 a == b が well-formed であって、 bool に変換可能 (しかし a < b はそうでない) であれば、
- a == b が true と等しければ、 std::strong_equality::equal を返します。
- そうでなければ、 std::strong_equality::nonequal を返します。
- そうでなければ (a <=> b と a == b がどちらも well-formed でない)、関数は削除されたものとして定義されます。
目次 |
[編集] 引数
| a, b | - | 比較する値 |
[編集] 戻り値
上で定義されている通り。
[編集] ノート
この関数は、 <=> が利用可能でないときはフォールバックとして < および == を使用するため、総称プログラミングで便利です。
[編集] 例
Run this code
#include <iostream> #include <compare> #include <algorithm> // <=> をサポートしない型。 struct Rational_1 { int num; int den; // > 0 }; inline constexpr bool operator<(Rational_1 lhs, Rational_1 rhs) { return lhs.num * rhs.den < rhs.num * lhs.den; } inline constexpr bool operator==(Rational_1 lhs, Rational_1 rhs) { return lhs.num * rhs.den == rhs.num * lhs.den; } // <=> をサポートする型。 struct Rational_2 { int num; int den; // > 0 }; inline constexpr std::weak_ordering operator<=>(Rational_2 lhs, Rational_2 rhs) { return lhs.num * rhs.den <=> rhs.num * lhs.den; } void print(std::weak_ordering value) { if (value == 0) std::cout << "equal"; else if (value < 0) std::cout << "less"; else std::cout << "greater"; std::cout << "\n"; } int main() { Rational_1 a{1,2}; Rational_1 b{3,4}; // print(a <=> b); // 動作しません。 print(std::compare_3way(a,b)); // 動作します。 < および == を使用します。 Rational_2 c{6,5}; Rational_2 d{8,7}; print(c <=> d); // 動作します。 print(std::compare_3way(c,d)); // 動作します。 }
出力:
less greater greater
[編集] 関連項目
| (C++20) |
三方比較を使用して2つの範囲を比較します (関数テンプレート) |
| (C++20) |
等しい、等しくないのみサポートする代用可能な三方比較の結果の型 (クラス) |
| (C++20) |
等しい、等しくないのみサポートする代用可能でない三方比較の結果の型 (クラス) |
| (C++20) |
6種類の演算子をすべてサポートする代用可能な三方比較の結果の型 (クラス) |
| (C++20) |
6種類の演算子をすべてサポートする代用可能でない三方比較の結果の型 (クラス) |
| (C++20) |
6種類の演算子をすべてサポートし、代用可能でなく、比較不可能な値を許容する、三方比較の結果の型 (クラス) |

