I’m having a problem that makes me feel rather daft. In a hobby project, I have a std::list of pointers to an interface class, which point to various concrete implementations of said interface.
For example, say I have the following:
class Seafood ...
class Fishstick : public Seafood ...
class Squid : public Seafood ...
...
std::list<Seafood*> buffet;
Now that I have my buffet populated by different seafood items, I want to count the number of fishsticks i have available to see if more needs to be ordered from the kitchen.
How would I do this without RTTI or some devious implementation thereof? I’ve read some articles that claim that if you find yourself wanting to use RTTI, you are approaching OOP the wrong way and/or your solution should be re-engineered. Are there some patterns or other solutions that deal with this problem? Which I’m sure has to surfaced many times before.
I was thinking the obvious which is some kind of virtual function, but I can’t figure out how to do this without building in a cheesy version of RTTI, or some knowledge about descendants into the interface (CountIfFishstick / IsFishstick / Is(type)).
edit: one other thing that came to mind would be to keep one list of fishsticks, one list of squid, etc. But that would surely defeat the whole purpose of interface/implemetation.
You probably want some variant of the visitor pattern. There are many and it’s hard to say which you want. I might recommend getting Modern C++ Design and reviewing Alexendrescu’s implementation. Otherwise, google “visitor pattern” and you’ll get 1000 km of links to read.