c++c++20pairwiseparameter-packtypelist

How to pairwise iterate over a type list and value list


I've got a typelist like

template <typename ...Types> struct type_list {};

and am looking for a way to iterate over pairs of elements from that type list and some value list from within a function like

template <typename ...Types, typename ...Values>
void f(type_list<Types...>, Values&&... values);

which is called like

template <int i, typename T> struct P {
    static constexpr int i = i;
    using type = T;
};
f(type_list<P<1, int>, P<3, double>>{}, 11, 12);

The lengths of the two lists are identical. The types in the typelist are unrelated to the values in the valuelist.

Maybe there's a way to zip the two lists into some type/value pair and fold that afterwards?


Solution

  • Just write an expression that contains both of the tokens Types and Values.

    Then put a ... after it in a context where such expressions can be expanded.

    As an example:

    template <typename ...Types, typename ...Values>
    void f(type_list<Types...> list, Values&&... values) {
    

    Make a tuple of Types, Values pairs:

      auto tup = std::tuple<std::pair<Types, Values>... >( {{}, std::forward<Values>(values)}... );
    

    Invoke code on each Type, Value corresponding pair, using ... fold-expansion of the , operator and a lambda:

      auto operation = [&]<class Type, class Value>()->void{
        std::cout << typeid(Type).name() << "," << typeid<Value>.name() << "\n";
      };
    
      (operation.template operator()<Types, Values>(), ...);
    }
    

    or whatever.