functional_identity

functional_identity (항등 함수 객체)

이 페이지는 C++20에서 도입된 std::identity 함수 객체에 대해 설명해요. std::identity는 주어진 인자를 수정 없이 그대로 돌려주는 단순한 함수 객체로, 주로 제약 알고리즘(constrained algorithms)에서 기본 투영(projection)으로 사용돼요. 직접 사용하기보다는 알고리즘의 기본 동작을 정의하는 역할을 해요.

출처: cppreference

본문

<functional> 헤더에 정의됨
struct identity ; (C++20부터)

std::identityoperator()가 인자를 변경하지 않고 그대로 반환하는 함수 객체 타입이에요.

멤버 타입 (Member types)

타입 정의
is_transparent 명시되지 않음 (unspecified)

멤버 함수 (Member functions)

| operator() | 인자를 그대로 반환해요 (공개 멤버 함수) |

std::identity::operator()

template < class T > constexpr T && operator ()( T && t ) const noexcept ;
std::forward<T>(t)를 반환해요.

매개변수 (Parameters)

| t | - | 반환할 인자 |

반환값 (Return value)

std::forward<T>(t)를 반환해요.

참고 (Notes)

std::identity는 제약 알고리즘에서 기본 투영(projection)으로 사용돼요. 직접 사용할 일은 보통 없어요.

예제 (Example)

#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 << '}';
    }
};

// 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&& 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("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}

같이 보기 (See also)

type_identity (C++20) 타입 인자를 그대로 반환해요 (클래스 템플릿) [edit]

더 알아보기 (Learn more)

cppreference