Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 subject 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

like image 347
Ben Crowhurst Avatar asked Dec 31 '10 07:12

Ben Crowhurst


1 Answers

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.

like image 154
James McNellis Avatar answered Oct 24 '22 00:10

James McNellis