std::compare_three_way_result

From cppreference.com
< cpp‎ | utility
 
 
 
Defined in header <compare>
template<class T, class U = T>
struct compare_three_way_result;
(since C++20)

Let t and u denote lvalue of const std::remove_reference_t<T> and const std::remove_reference_t<U> respectively, if the expression t <=> u is well-formed, provides the member typedef type equal to decltype(t <=> u), otherwise there is no member type.

Attempting to specialize this template results in undefined behavior.

Member types

Name Definition
type the result type of operator<=> on const-qualified lvalue of T and U

Helper types

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

Possible implementation

template<class T, class U = T>
struct compare_three_way_result {};
 
template<class T, class U>
    requires
        requires(const std::remove_reference_t<T>& t, const std::remove_reference_t<U>& u)
            { t <=> u; }
struct compare_three_way_result<T, U> {
    using type = decltype(std::declval<const std::remove_reference_t<T>&>() <=>
                          std::declval<const std::remove_reference_t<U>&>());
};

Example

#include <compare>
#include <type_traits>
#include <iostream>
 
template <class Ord>
void print_cmp_type()
{
    if constexpr (std::is_same_v<Ord, std::strong_ordering>)
        std::cout << "strong ordering\n";
    else if constexpr (std::is_same_v<Ord, std::weak_ordering>)
        std::cout << "weak ordering\n";
    else if constexpr (std::is_same_v<Ord, std::partial_ordering>)
        std::cout << "partial ordering\n";
    else if constexpr (std::is_same_v<Ord, std::strong_equality>)
        std::cout << "strong equality\n";
    else if constexpr (std::is_same_v<Ord, std::weak_equality>)
        std::cout << "weak equality\n";
    else
        std::cout << "illegal comparison result type\n";
}
 
int main()
{
    print_cmp_type<std::compare_three_way_result_t<int>>();
    print_cmp_type<std::compare_three_way_result_t<double>>();
    print_cmp_type<std::compare_three_way_result_t<int(*)()>>();
}

Output:

strong ordering
partial ordering
strong equality

See also

the result type of 3-way comparison that supports only equality/inequality and is not substitutable
(class)
the result type of 3-way comparison that supports only equality/inequality and is substitutable
(class)
the result type of 3-way comparison that supports all 6 operators, is not substitutable, and allows incomparable values
(class)
the result type of 3-way comparison that supports all 6 operators and is not substitutable
(class)
the result type of 3-way comparison that supports all 6 operators and is substitutable
(class)