CoffeDeveloper
CoffeDeveloper

Reputation: 8315

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 < ? > 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?

Upvotes: 6

Views: 4341

Answers (6)

CoffeDeveloper
CoffeDeveloper

Reputation: 8315

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"

Upvotes: 0

Dan
Dan

Reputation: 13160

I need at least 1 shared_ptr to keep resources alive

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.

Upvotes: 0

bstamour
bstamour

Reputation: 7766

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.

  1. If your list of types is finite, use boost::variant. e.g.

    std::vector<std::shared_ptr<boost::variant<int, float>>>;
    
  2. If you want to store anything, use boost::any. e.g.

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

Upvotes: 7

John Dibling
John Dibling

Reputation: 101456

No, C++ does not have a single type from which everything is derived like many other languages do. int and float are native types, meaning they are fundamental to the language and not derived from anything else.

If you have the benefit of Boost, you can store any or variant types in your vector instead.

Upvotes: 0

rectummelancolique
rectummelancolique

Reputation: 2237

You can't mix types like that. You may want to have a look at boost::any

Upvotes: 0

Viktor Sehr
Viktor Sehr

Reputation: 13099

I you really need to do exactly this, use boost::any.

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

Upvotes: 0

Related Questions