I have a problem which seems simple, but I can’t find an elegant solution for it.
I’m using a linked list which I need to sort twice:
- once on one parameter as list elements are added, and
- once on a different parameter after some processing.
The objects I store in the list inherit from an abstract list item base class.
The problem is with resorting on the second parameter. I don’t want to write a pure virtual accessor for it in the list item base class, because I later store some other objects in the list which also inherit from the list item base class, but the second accessor wouldn’t make sense for them.
Is there a clean solution that I’m missing?
If I understand correctly, you’ve something like that :
And you have a
std::list<Base*> myListsomewhere. The first time you want to sort your list, you do something like :And for the second sort, you need to use something specific to the class
Derived. You don’t want to add a pure virtual accessorgetParam2()intoBase& implement it inDerived. But if you know that your list contains only Derived objets, you can use a cast without problem :Note that if an object of your list is not a
Derived, dynamic_cast will returnnullptrso you can safely check it.