c++ - 在可变数据结构中初始化共享指针 vector

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

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

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

是否可以使用包扩展设置 vector 中的项目?以下不编译,但你明白了。参数列表也很好。

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

无论如何,感谢您对替代方案的投入或建议。

最佳答案

您的尝试几乎是正确的。您只是缺少 () 来调用 make_shared:

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

关于c++ - 在可变数据结构中初始化共享指针 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52248446/

相关文章:

c++ - 为什么以下代码会产生段错误?

c++ - Arduino编程错误

c++ - 使用可变参数将函数转换回原始签名

c++ - 在 C++03 和 C++14 的代码中进行简单随机改组的最佳做法是什么?

c++ - 使用类内成员初始化委托(delegate)构造函数

c++ - 无法访问同一类的私有(private)成员

c++ - 如何将模板类的内部类分离到其他文件中

c++ - lambda 函数中的 [=] 和 [&] 有什么区别吗?

templates - 如何在 CouchDB 中使用 html 模板

c++ - 模板 :Name resolution -->can any one tell some more examples for this statement?