简体   繁体   English

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

[英]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. 无论如何,感谢您的输入或其他建议。

Your attempt is almost right. 您的尝试几乎是正确的。 You're just missing () to call make_shared : 您只是缺少()来调用make_shared

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM