Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::ranges::greater — comparing in descending order

std::ranges::greater is a function object from <functional> that compares two arguments in the reverse order of std::ranges::less. It requires compatible comparison operations described by std::totally_ordered_with.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <functional>
std::ranges::greater{}(a, b)

std::ranges::greater is a function object type from <functional>, not a class template. The expression std::ranges::greater{}(a, b) creates an object and invokes its templated operator(), which returns bool and is constexpr.

The call is equivalent to std::ranges::less{}(std::forward<U>(u), std::forward<T>(t)): it reverses the arguments while preserving their value categories. For ordinary numbers, this tests whether the first argument is greater; equal values produce false. Pointer comparisons use the implementation-defined total order employed by std::ranges::less.

The argument types must satisfy the constraint std::totally_ordered_with<T, U>. Defining only operator> is insufficient: compatible equality and relational comparisons and a suitable common reference are also required. Syntactic validity does not replace the semantic ordering requirements.

The type exposes the marker is_transparent, so it does not fix a single argument type; different types must still satisfy the constraints. Unlike std::greater<T>, it takes no class-template argument. The example demonstrates greater, smaller, and equal values, along with compile-time checks.

Examples

#include <functional>
#include <iostream>

int main() {
    constexpr std::ranges::greater greater{};
    static_assert(greater(9, 4));
    static_assert(!greater(4, 4));

    std::cout << std::boolalpha
              << greater(9, 4) << '\n'
              << greater(4, 9) << '\n'
              << greater(4, 4) << '\n';
}

Result

true
false
false

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources