identity Структура

std::identity (представлено в C++20) — это объект функции, возвращающий operator() его аргумент без изменений.

Замечание

Существует структура identity Майкрософт из <utility>, которая устарела и недоступна в более поздних версиях Visual Studio. Для C++20 и более поздних версий используется std::identity<functional> вместо этого, что является стандартным эквивалентом, описанным ниже.

std::identity (C++20)

Многие API стандартной библиотеки принимают вызываемый аргумент, например проекцию или функцию преобразования. Если необходимо передать вызываемый объект, но не хотите изменять данные, передайте std::identity. Это распространено в алгоритмах диапазонов. Многие <algorithm> перегрузки диапазонов имеют параметр проекции, который по умолчанию имеет std::identity{}значение .

Синтаксис

struct identity
{
    template <class T>
    _NODISCARD constexpr T&& operator()(T&& t) const noexcept;
    using is_transparent = int;
};

Замечания

is_transparent Тип члена — это тег, который помечает std::identity как прозрачный объект функции. Его присутствие указывает, что алгоритмы могут выполнять сравнения или проекции без необходимости преобразовывать типы в общую форму. Это полезно для ассоциативных контейнеров и алгоритмов, поддерживающих разнородный поиск, что позволяет сравнивать различные типы напрямую без создания временных объектов.

Примеры

#include <algorithm>
#include <functional>
#include <iostream>
#include <ranges>
#include <vector>

int main()
{
    std::vector<int> v{3, 1, 4, 1, 5, 9, 2, 6};

    // Ranges algorithms can apply a projection before comparison.
    // But if you don't want to apply a projection, i.e. you don't want to modify the data
    // before comparison, you can use std::identity to leave each element unchanged.
    // Here, std::identity{} means "project each element as itself".
    // So the comparator sees the original int values unchanged.
    std::ranges::sort(v, std::less{}, std::identity{});

    // This call is equivalent because std::identity{} is the default projection.
    // In both calls, elements are sorted directly; no field extraction or
    // value transformation happens first.
    std::ranges::sort(v);

    for (int n : v)
    {
        std::cout << n << ' ';
    }
    std::cout << '\n';
    // Output: 1 1 2 3 4 5 6 9
}

В этом примере выполняется std::vector<std::string> поиск ключа std::string_view . Так как std::identity имеет is_transparent член, алгоритм знает, чтобы сравнить эти типы напрямую. Таким образом ключ не преобразуется во временный std::string просто для сравнения.

#include <algorithm>
#include <functional>
#include <iostream>
#include <ranges>
#include <string>
#include <string_view>
#include <vector>

int main()
{
    std::vector<std::string> words{"apple", "banana", "cherry", "date"};
    std::string_view key = "cherry";

    // `std::less<>` is transparent, so it can compare `std::string` and
    // `std::string_view` directly.
    // `std::identity` is also marked transparent (`is_transparent`), so the
    // projection stays type-flexible instead of forcing one fixed type.
    auto it = std::ranges::lower_bound(words, key, std::less<>{}, std::identity{});

    if (it != words.end() && *it == key)
    {
        std::cout << "Found: " << *it << '\n';
    }
}