Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 220
CoffeDeveloper Avatar asked Jun 24 '13 15:06

CoffeDeveloper


People also ask

Can a vector hold different data types in C++?

C++ is a statically-typed language. A vector will hold an object of a single type, and only a single type.

Why use shared pointer C++?

The shared_ptr type is a smart pointer in the C++ standard library that is designed for scenarios in which more than one owner might have to manage the lifetime of the object in memory.

When to use shared_ ptr?

Use shared_ptr to manage the lifetime of objects: Whose ownership is shared (multiple "things" want the object lifetime extended) Where the order of release of ownership is non-deterministic (you don't know in advance which of the owners will be "last" to release the object).

What is make_ shared in C++?

Description. It constructs an object of type T passing args to its constructor, and returns an object of type shared_ptr that owns and stores a pointer to it.


1 Answers

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>>;
    
like image 84
bstamour Avatar answered Sep 21 '22 12:09

bstamour