-2

I have this college project where I have to create a BinarySearchTree class using templates. We have to read a file and create the tree depending of the data type in the file. I made a parent class for the tree called BST so I can use the tree without giving it a class type.

class BST{
    public:
        BST();
        ~BST();
}

And the tree

template <class T> class BinarySearchTree : public BST{
    public:
        void add(T val);
}

And I wanted to do this:

BST tree = BinarySearchTree<int>(); //just an example, it can be of any type
tree.add(5); //doesn't work

How can I call "add" from BST without giving a specific variable type?

JCAguilera
  • 944
  • 1
  • 13
  • 32

2 Answers2

0

You have to make a virtual method in the class BST and also make BST a template.

virtual void add(T val) = 0;
Jake Freeman
  • 1,700
  • 1
  • 8
  • 15
-1

Use CRTP(Curiously Reccursive/Reccuring Template Pattern) and Concept Pattern.

https://qiita.com/Riyaaaa_a/items/a9af401520f238f45b80

This is written in Japanese, however, it's interesting!

yumetodo
  • 1,147
  • 7
  • 19