Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding different objects to std::list

Tags:

c++

can you add different class objects to same list?

like image 214
user35467 Avatar asked Dec 28 '22 09:12

user35467


2 Answers

See boost::any.

You can use std::vector and then use it to add heterogeneous types into.

Example:

std::vector<boost::any> v;
v.push_back(std::string("hello world"));
v.push_back(42);
like image 157
Scharron Avatar answered Jan 12 '23 15:01

Scharron


No, if they are unrelated objects. If they are related (i.e. have a common base class) then you can store the base class pointer (use smart pointers instead of raw pointers) in the list.

like image 38
Naveen Avatar answered Jan 12 '23 17:01

Naveen