Search code examples
c++templatesc++17variadic-templatestemplate-argument-deduction

How to write a function that takes a variadic number of array<double, N> and deduce N?


The goal is to have a function that takes an arbitrary number of array<double, N> of arbitrary size N (but this can be the same for all), and have N available inside the body of the function. For example let's say I want to return another user defined array type using N, MyArray<N>. I hope it's more clear! Thanks I am new to variadic templates and don't know how to do this. Any help or tip is appreciated. Thanks.

#include <array>
using namespace std;

template<int N>
struct MyArray {};

// here I don't know how to deduce N and keep the variadic number of parameters

template<int N, typename... Ts>
MyArray<N> foo(const Ts&... ts)
{ 
  // somehow use the variadic parameters
  MyArray<N> a;
  return a;
}

int main()
{
  array<double, 3> a, b, c;
  auto d = foo(a, b, c);
}

Solution

  • I finally managed to do it, the still bad element is that the type of N in the template part of Foo has to match exactly the type used in std::array to indicate the size, this makes N known inside and can be used to make a MyArray object.

    Basically I had to declare the parameter pack a template (thus having a template with a templated pack). Ts... is there because array normally takes more than 2 template parameters.

    #include <array>
    using namespace std;
    
    template<int N>
    struct MyArray {};
    
    template<typename T, long unsigned N, typename... Ts, template<typename, long unsigned, typename...> typename... Arrays>
    MyArray<N> Foo(const Arrays<T, N, Ts...>&... arrays)
    {
        return MyArray<N>{};
    }
    
    int main()
    {
        array<double, 3> a, b, c;
    
        MyArray<3> d = Foo(a, b, c);
        auto e = Foo(a, b);
    
        return 0;
    }