std::tuple_size

std::tuple_size (std::array 특수화)

std::tuple_sizestd::array에 대해 특수화한 템플릿이에요. 배열 안의 원소 개수를 컴파일 타임 상수식으로 알려줘요. tuple 같은 인터페이스에서 std::array의 크기를 정적으로 얻을 수 있게 해줘요.

출처: cppreference

본문

<array> 헤더에 정의돼 있고, std::array의 원소 개수에 대한 접근을 컴파일 타임 상수식으로 제공해요.

template< class T, std::size_t N >
struct tuple_size< std::array<T, N> > :
    std::integral_constant<std::size_t, N> { };

std::integral_constant<std::size_t, N>을 상속하므로, ::value::operator()로 그 값을 얻을 수 있어요. C++17부터는 헬퍼 변수 템플릿이 추가됐어요.

template< class T >
constexpr std::size_t tuple_size_v = tuple_size<T>::value;

std::integral_constant에서 상속받은 것들:

  • 멤버 상수 value [static]: 배열 안의 원소 개수 N이에요.
  • 멤버 함수 operator std::size_t: 객체를 std::size_t로 변환하며 value를 돌려줘요.
  • 멤버 함수 operator() (C++14): value를 돌려줘요.
  • 멤버 타입 value_type = std::size_t, type = std::integral_constant<std::size_t, value>.

예제를 보면요.

#include <array>

int main()
{
    auto arr = std::to_array("ABBA");
    static_assert(std::tuple_size<decltype(arr)>{} == 5);
}

"ABBA" 문자열 리터럴은 널 문자를 포함해 5개 원소를 가지는 std::array<char, 5>가 되므로, tuple_size 값은 5가 돼요. 이처럼 std::array의 크기를 컴파일 타임에 안전하게 알아낼 수 있어요.

더 알아보기 (Learn more)

cppreference