mercredi 28 avril 2021

How to access type's index in the template type parameter pack?

I would like to access type's index when expanding a type parameter pack into an std::tuple<...>.

For example, given a type pack of <int, double, float> I would like to build an std::tuple<...> that looks as follows:

std::tuple<std::array<int,0>, std::array<double,1>, std::array<float, 2>>
//                     ^  ^                ^    ^                ^    ^
//                     T  I                T    I                T    I

Here is an implementation that does almost exactly what I want, but it works only for type packs of size 3 (see the comment next to the hack). How do I fix this to work independently of TT...s size?

#include <tuple>
#include <utility>
#include <array>
#include <iostream>

template <typename... TT>
struct Foo {
    template <std::size_t... Indices>
    struct Baz {
       std::tuple<std::array<TT,Indices>...> baz;
    };
    Baz<0,1,2> bar; // <<<=== Here is the hack: I make a fixed-size pack; I want it to match TT...
};

int main() {
    Foo<int,double,float> foo;
    std::cout << std::get<0>(foo.bar.baz).size() << std::endl;
    std::cout << std::get<1>(foo.bar.baz).size() << std::endl;
    std::cout << std::get<2>(foo.bar.baz).size() << std::endl;
    return 0;
}

Live demo.

Aucun commentaire:

Enregistrer un commentaire