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* )
헤더 파일에 정의됨 <functional>
struct identity ;
(C++20부터)

std::identity 는 인자를 변경 없이 그대로 반환하는 operator ( ) 를 가지는 함수 객체 타입입니다.

목차

멤버 타입

유형 정의
is_transparent unspecified

멤버 함수

operator()
인수를 변경 없이 반환합니다
(public member function)

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>
struct Pair
{
    int n;
    std::string s;
    friend std::ostream& operator<<(std::ostream& os, const Pair& p)
    {
        return os << '{' << p.n << ", " << p.s << '}';
    }
};
// 범위의 투영된(수정된) 요소들을 출력할 수 있는 범위-프린터
template<std::ranges::input_range R,
         typename Projection = std::identity> //<- 기본 투영 함수 주목
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("std::identity를 투영 함수로 사용하여 출력: ", v);
    print("Pair::n을 투영: ", v, &Pair::n);
    print("Pair::s를 투영: ", v, &Pair::s);
    print("사용자 정의 클로저를 투영 함수로 사용하여 출력: ", 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}

참고 항목

타입 인자를 변경 없이 반환함
(클래스 템플릿)