Generic Container in C++
I'm attempting to create a generic container type to provide a single common interface, as well as hide the internal containers I'm using as they are subjec开发者_如何学Ct to change.
Basically I have plugins that return collections of items and I don't wish the plugins to be aware of the type of container my code is using.
Can anyone point me in a better direction then the example code below?
template<class C, typename I>
class Container
{
public:
//...
void push(const I& item)
{
if(typeid(C) == typeid(std::priority_queue<I>))
{
std::priority_queue<I>* container = (std::priority_queue<I>*)&_container;
container->push(item);
}
if(typeid(C) == typeid(std::list<I>))
{
std::list<I>* container = (std::list<I>*)&_container;
container->push_back(item);
}
else
{
//error!
}
};
private:
C _container;
//...
}
Thanks
I have plugins that return collections of items and I don't wish the plugins to be aware of the type of container my code is using.
Have your plugins provide begin
and end
iterators into their collections of items and then consume the range as you see fit.
The greatest advantage of iterators is that they allow complete decoupling of how the data is stored (the container) from how the data is used (the algorithm; in your case, your application code that consumes the plugin data).
This way, you don't have to care how the plugins store their data and the plugins don't have to care what you do with their data once they give it to you.
You know, when you wrote "common interface", I was sure you were going to show something Java style with an abstract class and subclasses that wrap standard containers. I was surprised to see a bunch of typeid calls...
But then, why do you want to do this? Most containers share a common interface, and with the power of SFINAE, you don't even have to write special code! Just use templates and call the method directly.
EDIT: Forgot that standard containers have no virtual methods and therefore, cannot be dynamic_cast
ed.
Start with a class as above, expose minimal interface needed by your plugins. Then implement it in terms of the container you are going to use. This is called container adapter and it is how std::stack is implemented.
If you really need adapter for more then one STL container go with template, have a look at std::stack, it will show how to do that.
Don't switch on typeid, why would you want that?
BTW, go with what James suggests unless there is a need to expose container itself.
精彩评论