Owenz
Owenz

Reputation: 44

List of multiple objects c++

I got some issues with the use of std::list. I can use it well with list of a "simple" type of data, or list of one type of object.

I want to create a list of three different types of objects. For example, there are three types of objects: class p1, class p2, class p3. And I want to create a list which contains objects of these three.

class p1 {
...
};

class p2 {
...
};

class p3 {
...
};

int main() {
    std::list<whatshouldiInserthere?> namelist;
}

I have already tried with template, but no way. Could you post an example source code?

Upvotes: 0

Views: 1662

Answers (2)

Blindy
Blindy

Reputation: 67380

  • You can use a list of void *, giving up on an elegant and modern solution
  • You could instead derive all your objects from a base class, then make your list contain pointers to that base class instead
  • You could use boost::variant or boost::any as a sort of a type safe void *. This is actually a lot better than it sounds because thanks to template magic it doesn't have extra indirection levels, and still doesn't require the same base class

Upvotes: 10

Paul
Paul

Reputation: 13238

whatshouldiInserthere does not exist. You need to store variants (like boost::variant, boost::any, etc.), which hold instances of your classes.

Upvotes: 2

Related Questions