types_type_identity

types_type_identity (타입 동일성)

이 페이지는 C++20에서 도입된 std::type_identity에 대해 설명해요. std::type_identity는 템플릿 인자 T를 그대로 멤버 typedef type으로 제공하는 간단한 변환 템플릿이에요. 주로 템플릿 인자 추론에서 비연역 문맥(non-deduced context)을 만들어 특정 인자가 추론되지 않도록 할 때 사용해요.

출처: cppreference

본문

<type_traits> 헤더에 정의되어 있어요. (since C++20)

template < class T > struct type_identity ;

이 템플릿은 T를 그대로 가리키는 멤버 typedef type을 제공해요. 즉, 항등 변환(identity transformation)을 수행하지요. 프로그램에서 std::type_identity에 대한 특수화를 추가하면 동작이 정의되지 않아요.

멤버 타입 (Member types)

이름 정의
type T

헬퍼 타입 (Helper types)

template < class T > using type_identity_t = type_identity < T >:: type ;

(since C++20)

가능한 구현 (Possible implementation)

template < class T > struct type_identity { using type = T ; };

참고 (Notes)

std::type_identity는 템플릿 인자 추론(template argument deduction)에서 비연역 문맥(non-deduced contexts)을 만드는 데 사용할 수 있어요.

기능 테스트 매크로 표준 기능
__cpp_lib_type_identity 201806L (C++20) std::type_identity

예제 (Example)

#include <iostream>
#include <type_traits>

template<class T>
T foo(T a, T b) { return a + b; }

template<class T>
T bar(T a, std::type_identity_t<T> b) { return a + b; }

int main()
{
    // foo(4.2, 1); // error, deduced conflicting types for 'T'
    std::cout << bar(4.2, 1) << '\n';  // OK, calls bar<double>
}

출력:

5.2

같이 보기 (See also)

identity (C++20) 인자를 변경하지 않고 그대로 반환하는 함수 객체 (클래스)

더 알아보기 (Learn more)

cppreference