Variadic template extension, inheritance and std :: unique_ptr

I have a code that works like this:

#include <memory>
#include <vector>

using namespace std;

struct A {
    virtual ~A() = default;
};

struct B : public A {
};

template<typename... Ts> struct C {
    C() : v_({new Ts...}) {}

    ...

    std::vector<A*> v_;
};

...

C<B, B, A> bba;

      

I would like to use std::unique_ptr

and std::make_unique

to avoid explicitly calling new

and iterating over v_

to remove it in the destructor ( v_

will std::vector<std::unique_ptr<A>>

), but can't figure out how to get married std::make_unique

with an initialization list and variadic expansion (I suspect it std::unique_ptr

's just to move). Any suggestions?

+3


source to share


1 answer


How about a constructor C

like below?

   // C++11 version (std::make_unique() unavailable in C++11)
   C()
    { 
      using unused = int[];

      v_.reserve(sizeof...(Ts));

      (void)unused { 0, ( v_.emplace_back( new Ts ), 0 )... };
    }

   // C++14 version
   C()
    { 
      using unused = int[];

      v_.reserve(sizeof...(Ts));

      (void)unused { 0, ( v_.emplace_back( std::make_unique<Ts>() ), 0 )... };
    }

      

Starter 0

at unused

(a suggestion from aschepler (thanks!)) Lets you define



C<> etl; 

      

with an empty list of types for C

.

+3


source







All Articles