Namespaces
Variants

std:: identity

From cppreference.net
Utilities library
Function objects
Function invocation
(C++17) (C++23)
Identity function object
identity
(C++20)
Old binders and adaptors
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
( until C++17* ) ( until C++17* )
( until C++17* ) ( until C++17* )

( until C++17* )
( until C++17* ) ( until C++17* ) ( until C++17* ) ( until C++17* )
( until C++20* )
( until C++20* )
Definiert im Header <functional>
struct identity ;
(seit C++20)

std::identity ist ein Funktionsobjekttyp, dessen operator ( ) sein Argument unverändert zurückgibt.

Inhaltsverzeichnis

Mitgliedertypen

Typ Definition
is_transparent unspecified

Memberfunktionen

operator()
gibt das Argument unverändert zurück
(öffentliche Elementfunktion)

std::identity:: operator()

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

Gibt std:: forward < T > ( t ) zurück.

Parameter

t - zurückzugebendes Argument

Rückgabewert

std:: forward < T > ( t ) .

Hinweise

std::identity dient als Standardprojektion in constrained algorithms . Seine direkte Verwendung ist normalerweise nicht erforderlich.

Beispiel

#include <algorithm>
#include <functional>
#include <iostream>
#include <ranges>
#include <string>
struct Pair
{
    int n;
    std::string s;
    friend std::ostream& operator<<(std::ostream& os, const Pair& p)
    {
        return os << '{' << p.n << ", " << p.s << '}';
    }
};
// Ein Bereichs-Drucker, der projizierte (modifizierte) Elemente eines Bereichs drucken kann.
template<std::ranges::input_range R,
         typename Projection = std::identity> //<- Beachten Sie die Standardprojektion
void print(std::string_view const rem, R&& range, Projection projection = {})
{
    std::cout << rem << '{';
    std::ranges::for_each(
        range,
        [O = 0](const auto& o) mutable { std::cout << (O++ ? ", " : "") << o; },
        projection
    );
    std::cout << "}\n";
}
int main()
{
    const auto v = {Pair{1, "one"}, {2, "two"}, {3, "three"}};
    print("Drucken mit std::identity als Projektion: ", v);
    print("Projiziere Pair::n: ", v, &Pair::n);
    print("Projiziere Pair::s: ", v, &Pair::s);
    print("Drucken mit benutzerdefinierter Closure als Projektion: ", v,
        [](Pair const& p) { return std::to_string(p.n) + ':' + p.s; });
}

Ausgabe:

Drucken mit std::identity als Projektion: {{1, one}, {2, two}, {3, three}}
Projiziere Pair::n: {1, 2, 3}
Projiziere Pair::s: {one, two, three}
Drucken mit benutzerdefinierter Closure als Projektion: {1:one, 2:two, 3:three}

Siehe auch

gibt den Typ-Parameter unverändert zurück
(Klassen-Template)