본문 바로가기
코드

make_index_sequence 구현

by ehei 2021. 1. 27.

tuple 출력에 이어 또 다시 과제를 풀어보았다. 이번에는 std::make_index_sequence를 구현해보는 것이었다. 이걸 처음 썼을 때는 왜 std::make_index_sequence로 만든 인스턴스를 넘겨줘야 하는지 이해하지 못했다. 왜냐하면 템플릿 인자로도 충분하다고 생각했기 때문이다. 그러나 구현해보니 이해가 되었다. 템플릿 함수의 템플릿 인자여도 가능할 것이다. 템플릿 인자로 넘겨줄 경우 안에 들어있는 파라미터 팩을 꺼내려면 조금 까다로운 코딩이 필요할 것이다. 즉 make_index_sequence의 로직이 반복될 것이다. 별도로 분리한 결과 [0 ... n] 인자를 넘기는 방식에 대해 더 간단하고 쉬운 해결책을 표준은 제시했다. 

 

이제 다시 강의를 들어야겠다.

template<size_t T,  size_t...Ts>
struct index_seq : index_seq<T - 1, T, Ts...>
{
    using type = typename index_seq<T - 1, T, Ts...>::type;
};

template<size_t...Ts>
struct index_seq<0, Ts...>
{
    using type = index_seq<0, Ts...>;
};

template<size_t MAX>
struct _make_index_seq : index_seq<MAX - 1>
{
    using type = typename index_seq<MAX - 1>::type;
};

template<size_t MAX>
using make_index_seq = typename _make_index_seq<MAX>::type;

template<size_t...Ts>
std::ostream& operator<<( std::ostream& os, index_seq<Ts...> )
{
    return ((os << Ts << " "),...);
}

int main()
{  
    std::cout << make_index_seq<4>{} << std::endl;
    return 0;
}

 

'코드' 카테고리의 다른 글

메모리  (0) 2021.02.15
alignas  (0) 2021.02.03
tuple 출력  (0) 2021.01.22
std::remove_if  (0) 2021.01.21
instance in underlying array  (0) 2021.01.21