在varidic数据结构中初始化共享指针的向量

问题描述 投票:0回答:1

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

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

无论如何,感谢您对替代品的意见或建议。

c++ c++11 templates variadic-templates initializer-list
1个回答
4
投票

你的尝试几乎是对的。你只是缺少()来打电话给make_shared

template<class ...t>
struct collection2 {
  collection2() : a{ make_shared<derived<t>>()... } {};
  ~collection2() {};
  vector<shared_ptr<base>> a;
};
© www.soinside.com 2019 - 2024. All rights reserved.