初始化变异数据结构中共享指针的向量

时间:2018-09-09 20:31:38

标签: c++ c++11 templates variadic-templates initializer-list

我在玩可变的结构,就像一个拿着火柴盒的孩子。目标是使用参数包扩展来初始化基类指针的向量。 鉴于:

   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;
     ...
   };

是否可以使用包扩展设置矢量中的项目?以下内容无法编译,但是您可以理解。参数列表也很好。

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

所以您应该可以这样声明它:

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

无论如何,谢谢您的建议或建议。

1 个答案:

答案 0 :(得分:4)

您的尝试几乎是正确的。您只是想念()来打电话给make_shared

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