Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::less — typed and transparent comparison

std::less from <functional> is a comparison function object. std::less<T> accepts arguments as const T&, whereas std::less<void>, also written std::less<>, deduces their types independently. Its is_transparent marker enables heterogeneous lookup.

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

Syntax

#include <functional>
std::less<T>{}(a, b)
std::less<void>{}(a, b) // same specialization as std::less<>
using Marker = std::less<void>::is_transparent;

std::less is a comparator template from <functional>. For a concrete type T, its operator() accepts two const T& arguments and returns bool. Arguments may therefore be converted to T before comparison.

std::less<void> and std::less<> name the same specialization. It deduces each argument type independently, forwards arguments preserving their value categories, and uses <; the result type comes from that expression and need not be bool.

std::less<void>::is_transparent is a nested type alias with an unspecified underlying type, not a Boolean flag. Its presence enables heterogeneous lookup overloads in ordered associative containers. Comparisons between the relevant types must still be valid and consistent with the container's ordering; the marker does not check this.

A container comparator must induce a strict weak ordering. For pointers, std::less<T*> provides an ordering consistent with the implementation-defined strict total order. This also applies to std::less<> when it uses a built-in pointer comparison; do not assume an ordering of unrelated objects across runs.

Examples

#include <functional>
#include <iostream>
#include <set>

int main() {
    using Marker = std::less<void>::is_transparent;
    static_assert(requires { typename Marker; });

    std::cout << std::boolalpha;
    std::cout << std::less<int>{}(2, 2.5) << '\n';
    std::cout << std::less<>{}(2, 2.5) << '\n';

    const std::set<int, std::less<>> values{1, 2, 3};
    std::cout << (values.find(2.5) == values.end()) << '\n';
}

Result

false
true
true

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