Given following problem:
class Instrument {
};
class Guitar : public Instrument {
public:
void doGuitar() const;
};
class Piano : public Instrument {
public:
void doPiano() const;
};
I got a list of pointers to Instrument
list<shared_ptr<Instrument>> instruments;
in which i add instruments via (for example)
Guitar myGuitar;
instruments.push_back(make_shared<Guitar>(myGuitar));
Now, I want to iterate over the list instruments
and call doPiano()
iff the current instrument is a piano and doGuitar()
iff it is a guitar. These two functions differ a lot and thus, cannot be made abstract in class Instrument
.
The problem is that C++ won't be able to identify the type of the Instrument
by runtime, isn't it (due to single dispatch)? How can I achieve that it calls the piano- or the guitar-function depending on the current type the iterator is pointing at.
I would be happy if I could implement sth. working like this pseudo-code:
list<shared_ptr<Instrument>>::const_iterator it;
if ("current type == Guitar")
(*it)->doGuitar();
else if ("current type == Piano")
(*it)->doPiano();
Result
Actually, I ran into several problems with my approach. I did much refactoring using this post: How does one downcast a std::shared_ptr? . Thanks to all for your help :)