Search code examples
c++templatesvariadic-templates

How to zip vectors using template metaprogramming


I am practicing on template meta-programming and wanted to implement a simple trivial meta-function. I wonder how one can implement zip functionality on custom vectors. What I have in my mind is as follows:

Here is how the zip operation for this custom vector look like:

Inputs:

Vector<1, 2, 3>
Vector<2, 3, 4>
Vector<3, 4, 5>

Output:

Vector<6, 24, 60>

I believe my Vector class should be declared like:

template<int... vals>
struct Vector;

zip meta-function should have the signature:

template<typename... Vectors>
struct zip
{
    ///
}

I cannot figure out how to multiply values in the input vectors that happen to be in the same index via template meta-programming?


Solution

  • You can partially specialise zip in order to expose the template parameters of the Vectors you pass.

    template<typename...>
    struct zip;
    
    template<int... Us, int... Vs, typename... Tail>
    struct zip<Vector<Us...>, Vector<Vs...>, Tail...> {
        using type = typename zip<Vector<(Us * Vs)...>, Tail...>::type;
    };
    
    template<typename T>
    struct zip<T> {
        using type = T;
    };
    
    static_assert(std::is_same<zip<Vector<2, 4, 6>, 
                                   Vector<1, 2, 3>, 
                                   Vector<3, 6, 9>>::type, 
                                   /* == */ Vector<6, 48, 162>>::value);