mardi 22 mars 2022

How to avoid including header files of inherited classes?

I want to make a static library that performs Binary Search Tree operations. But I want that BST perform operations both iteratively and recursively.

To do that I created a interface called IBST. And I made that template because I want that BST should support multiple data types.

template <class T>
class IBST
{
  virtual ~IBST { }
  virtual bool insertElement(T value) = 0;
  virtual bool searchElement(T value) = 0;
  virtual bool removeElement(T value) = 0;
};

After that I created two new header files IterativeBST.h and RecursiveBST.h which are inherited from IBST

template <class T>
    class IterativeBST : public IBST<T>
    {
     private:
      Node <T>* root;
     public:
       IterativeBST { }
       virtual ~IterativeBST{ }
       bool insertElement(T value)
       {
        // some operations
       }
       bool searchElement(T value)
       {
        // some operations
       }
       bool removeElement(T value)
       {
        // some operations
       }
    };

This is the Iterative.h file. There is also a RecursiveBST.h file that works the same way, but I don't add it so it won't get crowded.

Finally I have Node.h file which is used for basic structure of BST

template <class T>
    class Node
    {
     private:
      T value;
      Node *left;
      Node *right;

     public:
     // some get set methods and consructor, destructor
    };

After creating this header files, I decided to use factory pattern to decide which implementation(recursive or iterative) will be used.

#include <IBST.h>
#include <IterativeBST.h>
#include <RecursiveBST.h>

template <class T>
     class BSTFactory
      {
          //constructor and desctuctor
          
          IBST<T>* getBST(int input)
          {
             // if input something return new IterativeBST<T>

             //else return new RecursiveBST<T>
          }
      };

These header files are all in static library project. I've just used header files because I used template classes.

Finally I want to use this static library from a executable project. It happens something like this;

#include <IBST.h>
#include <IterativeBST.h>
#include <RecursiveBST.h>
#include <BSTFactory.h>

int main()
{
BSTFactory<int>* factory = new BSTFactory<int>();
IBST<int>* bst = factory->getBST(input);

//bst->insert    bst->remove() goes on like this
}

My problem starts here. The Factory class has to include these files(IterativeBST.h and RecursiveBST.h) in order to return IterativeBST or RecursiveBST in the static library. I thought a solution would be to create BSTFactory.cpp and do the include operation there, but this is not possible since that is template class.

To summarize, I don't want IterativeBST.h and RecursiveBST.h inside the main function. Because I know it is a bad design. But I couldn't find how to solve this.

Aucun commentaire:

Enregistrer un commentaire