std::compare_three_way_result

来自cppreference.com
< cpp‎ | utility
 
 
工具库
语言支持
类型支持(基本类型、RTTI)
库功能特性测试宏 (C++20)
动态内存管理
程序工具
协程支持 (C++20)
变参数函数
调试支持
(C++26)
三路比较
compare_three_way_result
(C++20)
(C++20)
(C++20)(C++20)(C++20)
(C++20)(C++20)(C++20)
通用工具
日期和时间
函数对象
格式化库 (C++20)
(C++11)
关系运算符 (C++20 中弃用)
整数比较函数
(C++20)(C++20)(C++20)   
(C++20)
交换类型运算
(C++14)
(C++11)
(C++11)
(C++11)
(C++17)
常用词汇类型
(C++11)
(C++17)
(C++17)
(C++17)
(C++11)
(C++17)
(C++23)
初等字符串转换
(C++17)
(C++17)

 
在标头 <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 种运算符且可替换
(类)