Spec-Zone.ru › C++

std::identity

Определено в заголовке <functional>
struct identity;
(с C++20)

std::identity — это тип объекта-функции, чьё operator() возвращает свой аргумент без изменений.

Вложенные типы

Вложенный тип Определение
is_transparent неопределено

Члены-функции

operator()
возвращает аргумент без изменений
(публичный член-функция)

std::identity::operator()

template< class T >
constexpr T&& operator()( T&& t ) const noexcept;

Возвращает std::forward<T>(t).

Параметры

t - аргумент, который нужно вернуть

Возвращаемое значение

std::forward<T>(t).

Примечания

std::identity служит в качестве проекции по умолчанию в ограниченных алгоритмах. Его прямое использование обычно не требуется.

Пример

#include <algorithm>
#include <functional>
#include <iostream>
#include <ranges>
#include <string>
#include <vector>
 
struct Pair
{
    int n;
    std::string s;
    friend std::ostream& operator<<(std::ostream& os, const Pair& p)
    {
        return os << "{ " << p.n << ", " << p.s << " }";
    }
};
 
// A range-printer that can print projected (modified) elements of a range.
template<std::ranges::input_range R,
         typename Projection = std::identity> //<- Notice the default projection
void print(std::string_view const rem, R&& r, Projection proj = {})
{
    std::cout << rem << "{ ";
    std::ranges::for_each(r, [](const auto& o) { std::cout << o << ' '; }, proj);
    std::cout << "}\n";
}
 
int main()
{
    const std::vector<Pair> v{{1, "one"}, {2, "two"}, {3, "three"}};
 
    print("Print using std::identity as a projection: ", v);
    print("Project the Pair::n: ", v, &Pair::n);
    print("Project the Pair::s: ", v, &Pair::s);
    print("Print using custom closure as a projection: ", v,
        [](Pair const& p) { return std::to_string(p.n) + ':' + p.s; });
}

Вывод:

Print using std::identity as a projection: { { 1, one } { 2, two } { 3, three } }
Project the Pair::n: { 1 2 3 }
Project the Pair::s: { one two three }
Print using custom closure as a projection: { 1:one 2:two 3:three }

См. также

type_identity
(C++20)
возвращает аргумент-тип без изменений
(шаблон класса)

© cppreference.com
Licensed under the Creative Commons Attribution-ShareAlike Unported License v3.0.
https://en.cppreference.com/w/cpp/utility/functional/identity

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API