c++c++17template-meta-programmingindex-sequence

How does std::index_sequence_for<T... >() exactly work?


I have the following code

#include<iostream>
#include <tuple>
#include<utility>
using namespace std::literals::string_literals;


template< typename tupleType, size_t ... inds >
void printTupleH(const tupleType& tuple, std::index_sequence<inds ...>){

    ((std::cout << std::get<inds>(tuple) << " "), ..., (std::cout << "\n"));
}


template< typename ... tupleElementsTypes>
void printTuple(const std::tuple<tupleElementsTypes ...>& tuple){

    printTupleH< std::tuple<tupleElementsTypes ...>, std::index_sequence_for<tupleElementsTypes... >()  >(tuple, std::index_sequence_for<tupleElementsTypes...>() );
}


int main() {
    auto myTuple{std::make_tuple(1, 0.5, "erfevev"s, "dsfgsfgsf",'g',true,0x44,999999999999999999,9.999999999)};

    printTuple(myTuple);

}

I don't know what's wrong with this

printTupleH< std::tuple<tupleElementsTypes ...>, std::index_sequence_for<tupleElementsTypes... >()  > As the IDE says.

When I leave the function call without any template args the deduction works well.

What I know is std::index_sequence_for<tupleElementsTypes... >() should expand to 0,1,2,..N-1 . So what's wrong.


Solution

  • printTupleH's template definition expects a list of std::size_t. std::index_sequence_for creates a single std::integer_sequence (more precisely, a std::index_sequence, which is just an alias for integer sequences of std::size_t), not a list of sizes.

    To explicitly add the deduction you would need to manually provide a list of std::size_t, one for each index – which defeats the point of using an index sequence in the first place! It is intended to be used with template deductions.