Search code examples
c++variadic-templates

Storing variadic unique_ptr pack into a tuple


I am trying to write a constructor that takes a variadic pack of unique_ptrs as argument and store it in a tuple:

template<class... E>
    class A
    {
        std::tuple<std::unique_ptr<E>...> a_;

    public:
        A(std::unique_ptr<E>&&... a)
           : a_(std::make_tuple(std::move(a)...)) {}
  
    };

but this fails to compile when I call the constructor with more than one argument --- e.g.

A< double> obj(std::make_unique<double>(2.0), std::make_unique<double>(3.0));

fails to compile with an error in tuple::test_method().

My questions are:

  1. Is there anything inherently wrong in what I am trying to do?
  2. Is it doable?

Thanks


Solution

  • It looks like in this case the issue is just that your variable is type A<double> but you are passing two values, so you need to use A<double, double>.

    A<double, double> obj(std::make_unique<double>(2.0), std::make_unique<double>(3.0));
    

    Alternatively, you can eliminate the need to state template parameters if you declare the variable with auto.

    auto obj = A(std::make_unique<double>(2.0), std::make_unique<double>(3.0));