mardi 28 avril 2015

Generic design mixed with curiously recurring template pattern. C++

Consider this kind of problem. I have a Base class and three classes derived from Base. For instance: DerivedA, DerivedB and DerivedC. Each derived class has its unique container. Hence DerivedA has std::vector<int>, DerivedB has std::set<int> and DerivedC has std::map<int, std::string>. And I want an interface in Base to access the container of derived class on which it is currently pointed to.

Base* d1 = new DerivedA;
for(std::vector<int>::iterator iter = d1->begin(); iter != d1->end(); ++iter)
{
     //processing
}

I tried to wrap each container to separate class and keep a pointer of their base in the Base class.

class CollA;

template<class T>
class traits;

template<>
class traits<CollA>
{
  public:
  typedef vector<int> container; 
};


template<class T>
class Coll
{
  public:
    typedef typename traits<T>::container container;
    typename container::iterator begin() const
    {
    }
};


class CollA : public Coll<CollA>
{
  typedef traits<CollA>::container container;
  public:
    container::iterator begin()
    {
      return V.begin();
    }
    private:
    vector<int> V;
};

class Base
{
  public:
    Base()
    {
    }
    // what to do here? I must keep a pointer to Coll; But Coll itself is a template
};

Suggest me something. I am kind of lost in this horrible design.

Aucun commentaire:

Enregistrer un commentaire