Search code examples
c++c++11templatesvariadic-templatesinitializer-list

Initialize a vector of shared pointers in varidic data structures


I'm playing with variadic structures, and I'm like a kid with a box of matches. The goal is to initialize a vector of base class pointers using parameter pack expansion. Given:

   struct base {
     base() {};
     virtual ~base() {};
     ...
   };

   template<class T>
   struct derived : public base {
     derived() {};
     virtual ~derived() {};
     ...
   };

   struct collection {
     collection() 
       : a{ make_shared<derived<int>>(),
            make_shared<derived<float>>(),
            make_shared<derived<double>>() } {};
     ~collection() {};
     vector<shared_ptr<base>> a;
     ...
   };

Is it possible to set the items in the vector using pack expansion? The following doesn't compile, but you get the idea. Argument lists would also be nice.

    template<class ...t>
    struct collection2 {
      collection2() : a{ make_shared<derived<t>>... } {}; //????
      ~collection2() {};
      vector<shared_ptr<base>> a;
    };

So you should be able to declare it like this:

    int main() {
      collection2<int,float,double> a;
      return 0;
    }

Anyway thanks for your input or suggestions to alternatives.


Solution

  • Your attempt is almost right. You're just missing () to call make_shared:

    template<class ...t>
    struct collection2 {
      collection2() : a{ make_shared<derived<t>>()... } {};
      ~collection2() {};
      vector<shared_ptr<base>> a;
    };