简体   繁体   English

C ++如何在shared_ptrs的向量中存储多个类型?

[英]C++ How can I store multiple types in an vector of shared_ptrs?

How can I store in a std::vector multiple shared_ptr each one with a pointer to a different type? 如何在std :: vector中存储多个shared_ptr,每个都有一个指向不同类型的指针?

std::vector < ? > vec;
vec.push_back( make_shared<int>(3));
vec.push_back( make_shared<float>(3.14f));

Is there a base polymorphic class that can I use for that task without having to use compiler-specific stuff? 是否有一个基本的多态类可以用于该任务而不必使用特定于编译器的东西?

There are a few ways you can do this. 有几种方法可以做到这一点。 I assume you want to store various native types, as you're using int and float. 我假设您要存储各种本机类型,因为您使用的是int和float。

  1. If your list of types is finite, use boost::variant . 如果您的类型列表是有限的,请使用boost :: variant eg 例如

     std::vector<std::shared_ptr<boost::variant<int, float>>>; 
  2. If you want to store anything, use boost::any . 如果你想存储任何东西,请使用boost :: any eg 例如

     std::vector<std::shared_ptr<boost::any>>; 

I you really need to do exactly this, use boost::any . 我真的需要这样做,使用boost :: any

And use std::vector <std::shared_ptr<boost::any> > vec; 并使用std::vector <std::shared_ptr<boost::any> > vec;

You can't mix types like that. 你不能混合这样的类型。 You may want to have a look at boost::any 你可能想看一下boost :: any

No, C++ does not have a single type from which everything is derived like many other languages do. 不,C ++没有像许多其他语言那样派生所有内容的单一类型。 int and float are native types , meaning they are fundamental to the language and not derived from anything else. intfloat本机类型 ,这意味着它们是语言的基础,而不是从其他任何东西派生的。

If you have the benefit of Boost, you can store any or variant types in your vector instead. 如果您拥有Boost的优势,则可以在vector存储anyvariant类型。

I need at least 1 shared_ptr to keep resources alive 我需要至少1个shared_ptr来保持资源的存活

For this to work, all the types you store must inherit from the same base class, which is the same type as the type contained in the shared pointer. 为此,您存储的所有类型都必须从相同的基类继承,该基类与共享指针中包含的类型相同。 Additionally, the base class must declare a virtual destructor (see this question ). 此外,基类必须声明一个虚拟析构函数(请参阅此问题 )。

Using boost::any will mean that every other shared_ptr to the objects also has to be a shared_ptr<bsst::any> , which is likely not what you want. 使用boost::any意味着对象的每个其他shared_ptr也必须是shared_ptr<bsst::any> ,这可能不是你想要的。

A possible way I figured to solve that is by doing the following 我想通过以下方式解决这个问题的可行方法

class ISomething{
    bool isAlive;
public:
    virtual bool alive(){ return isAlive;}
    virtual ~ISomething() {}
};

template <typename T>
class Something: public ISomething{
    std::shared_ptr<T> myRes;
public:    
};

std::vector<ISomething*> myVec; //push back a new dynamic allocation for each "Something"

That's basically type erasure, the same concept behind " Boost::Any " " Poco::Any " " Ogre::Any " 这基本上是类型擦除,“ Boost :: Any ”背后的相同概念“ Poco :: Any ”“ Ogre :: Any

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

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