Antony Tren'kin
Antony Tren'kin

Reputation: 63

different types of objects in std::vector or another data structure

I want to store such structure

  template <typename var_type> struct
  {
  int some_var;
  //...some antoher vars
  var_type problem_var;
  };

in vector or something like vector, how can i do that? I can't create vector with template content

Upvotes: 0

Views: 191

Answers (3)

MSalters
MSalters

Reputation: 179799

If you know the list of types up front, boost::variant<> can be more suitable than boost::any. In your case, you might need

typedef boost:variant<
   mystruct<float>,
   mystruct<int>
   mystruct<std::string>
> my_variant;

This will allow only these 3 types. Alternatively, you might want mystruct<boost:variant<float, int, std::string> >, which is superficially similar. I can't judge from your question which would be most suited to your problem.

Upvotes: 5

Vincenzo Pii
Vincenzo Pii

Reputation: 19805

Can't you create a class hierarchy with the type of objects you need to store and always upcast to the base class when inserting into the vector?

The drawback is that you always have to know what type to downcast to when extracting items from the vector or using the base class interface (probably a getter method).

Upvotes: 0

Archie
Archie

Reputation: 6844

You can use something like Boost.Any.

Upvotes: 1

Related Questions