types_rank

types_rank (배열 차원 수를 얻는 타입 특성)

std::rank는 주어진 타입이 배열 타입일 때 그 배열의 차원 수를 알려주는 C++ 타입 특성(type trait)이에요. 배열이 아닌 타입에 대해서는 value가 0이 돼요. 이 페이지에서는 std::rank의 정의, 헬퍼 변수 템플릿, 상속 구조, 구현 예시를 함께 살펴봐요.

출처: cppreference

본문

헤더와 기본 정의

<type_traits> 헤더에 정의되어 있으며, C++11부터 사용할 수 있어요.

정의
template < class T > struct rank; (since C++11)

T가 배열 타입이라면, 배열의 차원 수에 해당하는 멤버 상수 value를 제공해요. 다른 모든 타입에 대해서는 value가 0이에요.

프로그램에서 std::rank 또는 std::rank_v(C++17부터)에 대해 특수화를 추가하면 동작이 정의되지 않아요.

헬퍼 변수 템플릿 (Helper variable template)

C++17부터 rank_v 변수 템플릿을 사용할 수 있어요.

정의
template < class T > constexpr std::size_t rank_v = rank<T>::value; (since C++17)

std::integral_constant로부터 상속

std::rankstd::integral_constant<std::size_t, value>를 상속받아요. 따라서 다음 멤버들을 사용할 수 있어요.

멤버 상수

이름 설명
value [static] T의 차원 수 또는 0 (공용 정적 멤버 상수)

멤버 함수

함수 설명
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>

가능한 구현 (Possible implementation)

다음은 std::rank의 동작을 보여주는 예시 구현이에요.

template < class T > struct rank : public std :: integral_constant < std :: size_t , 0 > {};
template < class T > struct rank < T [] > : public std :: integral_constant < std :: size_t , rank < T >:: value + 1 > {};
template < class T , std :: size_t N > struct rank < T [ N ] > : public std :: integral_constant < std :: size_t , rank < T >:: value + 1 > {};

예제 (Example)

#include <type_traits>

static_assert(std::rank<int>{} == 0);
static_assert(std::rank<int[5]>{} == 1);
static_assert(std::rank<int[5][5]>{} == 2);
static_assert(std::rank<int[][5][5]>{} == 3);

int main()
{
    [[maybe_unused]] int ary[][3] = {{1, 2, 3}};

    // The rank of reference type, e.g., ary[0], that is int(&)[3], is 0:
    static_assert(std::rank_v<decltype(ary[0])> == 0);
    static_assert(std::is_same_v<decltype(ary[0]), int(&)[3]>);

    // The solution is to remove the reference type.
    static_assert(std::rank_v<std::remove_cvref_t<decltype(ary[0])>> == 1);
}

같이 보기 (See also)

이름 설명
is_array (C++11) 타입이 배열 타입인지 확인해요. (클래스 템플릿)
extent (C++11) 배열 타입의 특정 차원 크기를 구해요. (클래스 템플릿)
remove_extent (C++11) 주어진 배열 타입에서 한 차원을 제거해요. (클래스 템플릿)
remove_all_extents (C++11) 주어진 배열 타입에서 모든 차원을 제거해요. (클래스 템플릿)
rank (C++26) 반영된 배열 타입의 차원 수를 구해요. (함수)

더 알아보기 (Learn more)

cppreference