vendredi 22 mai 2015

Recursively getting item from nested generic data structure

I'm trying to build a generic container class using templates so that I can store an arbitrary data type in the container. I have a generic interface class with a virtual "get" method that returns an object of the parametrized type. One common use of this container will be to create a "container-of-containers" with 2 or more levels. What I'd like to do is provide a recursive "get" method that will traverse the hierarchy and return an item from a leaf node.

Here is some example code showing what I'm trying to do:

#include <iostream>

template<typename DataT>
class container_intf
{
   public:

      container_intf() = default;
      virtual ~container_intf() = default;
      virtual DataT get() = 0;
};

class one : public container_intf<int>
{
   public:
      int get() { return 1; };
};

class two : public container_intf<int>
{
   public:
      int get() { return 2; };
};


template<typename DataT>
class generic : public container_intf<DataT>
{
   public:
      DataT get()
      {
         return DataT();
      };
};


int main(int argc, char** argv)
{
   one o;
   two t;
   std::cout << o.get() << "\n";
   std::cout << t.get() << "\n";


   generic<int> g;
   std::cout << g.get() << "\n";

   generic<one> one_nested;
   std::cout << one_nested.get().get() << "\n";


   generic< generic<two> > two_nested;
   std::cout << two_nested.get().get().get() << "\n";

   return 0;
};

Basically, I'd like to be able to call "two_nested.get()" instead of "two_nested.get().get().get()". I've tried using type traits and std::enable_if but I haven't been able to get it to work. A helper class or function would be fine; I just want to be able to support a hierarchy of arbitrary depth.

Aucun commentaire:

Enregistrer un commentaire