std::compare_three_way_result

来自cppreference.com
< cpp‎ | utility
 
 
 
在标头 <compare> 定义
template< class T, class U = T >
struct compare_three_way_result;
(C++20 起)

tu 分别代表 const std::remove_reference_t<T>const std::remove_reference_t<U> 类型的左值,若表达式 t <=> u 良构,则提供等于 decltype(t <=> u) 的成员 typedef type,否则无成员 type

如果程序添加了 std::compare_three_way_result 的特化,那么行为未定义。

目录

[编辑] 成员类型

名字 定义
type operator<=>TU 的 const 限定左值上的结果类型

[编辑] 辅助类型

template< class T, class U = T >
using compare_three_way_result_t = compare_three_way_result<T, U>::type;
(C++20 起)

[编辑] 可能的实现

// 由 Casey Carter 推荐
// 参阅:https://github.com/microsoft/STL/pull/385#discussion_r357894054
template<class T, class U = T>
using compare_three_way_result_t = decltype(
    std::declval<const std::remove_reference_t<T>&>() <=>
    std::declval<const std::remove_reference_t<U>&>()
);
 
template<class T, class U = T>
struct compare_three_way_result {};
 
template<class T, class U>
    requires requires { typename compare_three_way_result_t<T, U>; }
struct compare_three_way_result<T, U>
{
    using type = compare_three_way_result_t<T, U>;
};

[编辑] 示例

#include <compare>
#include <iostream>
#include <type_traits>
 
template<class Ord>
void print_cmp_type()
{
    if constexpr (std::is_same_v<Ord, std::strong_ordering>)
        std::cout << "强序\n";
    else if constexpr (std::is_same_v<Ord, std::weak_ordering>)
        std::cout << "弱序\n";
    else if constexpr (std::is_same_v<Ord, std::partial_ordering>)
        std::cout << "部分序\n";
    else
        std::cout << "非法的比较结果类型\n";
}
 
int main()
{
    print_cmp_type<std::compare_three_way_result_t<int>>();
    print_cmp_type<std::compare_three_way_result_t<double>>();
}

输出:

强序
部分序

[编辑] 参阅

三路比较的结果类型,支持所有 6 种运算符且不可替换,并允许不可比较的值
(类) [编辑]
三路比较的结果类型,支持所有 6 种运算符且不可替换
(类) [编辑]
三路比较的结果类型,支持所有 6 种运算符且可替换
(类) [编辑]