std::tuple_element
std::tuple_element (std::array 특수화)
std::tuple_element를 std::array에 대해 특수화한 템플릿이에요. 배열 원소의 타입을 컴파일 타임 인덱스로 접근할 수 있게 해줘요. tuple 같은 인터페이스에서 std::array를 함께 쓸 수 있게 하는 핵심이에요.
출처: cppreference
본문
<array> 헤더에 정의돼 있고, tuple 인터페이스로 배열 원소 타입에 컴파일 타임 인덱스 접근을 제공해요.
template< std::size_t I, class T, std::size_t N >
struct tuple_element< I, std::array<T, N> >;
- 멤버 타입
type: 배열 원소의 타입이에요.
즉 std::tuple_element<0, std::array<int,10>>::type은 int가 돼요. cv 한정(qualification)에 따라 결과 타입도 달라져요. 예를 들어 const std::array<int,10>에 대해서는 const int가 돼요.
가능한 구현은 아래와 같아요.
template<std::size_t I, class T>
struct tuple_element;
template<std::size_t I, class T, std::size_t N>
struct tuple_element<I, std::array<T,N>>
{
using type = T;
};
예제를 보면요.
#include <array>
#include <tuple>
#include <type_traits>
int main()
{
// 배열을 정의하고 0번 위치의 원소 타입 가져오기
std::array<int, 10> data{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
using T = std::tuple_element<0, decltype(data)>::type; // int
static_assert(std::is_same_v<T, int>);
const auto const_data = data;
using CT = std::tuple_element<0, decltype(const_data)>::type; // const int
// tuple_element의 결과는 tuple 같은 타입의 cv 한정에 따라 달라져요
static_assert(!std::is_same_v<T, CT>);
static_assert(std::is_same_v<CT, const int>);
}
이렇게 std::array도 tuple과 동일한 방식으로 원소 타입을 정적으로 꺼낼 수 있어요. 구조적 바인딩이나 std::apply 같은 일반화 코드가 std::array를 지원할 수 있는 바탕이 돼요.