Search code examples
c++templatespointersbinary-search-treedereference

Creating new instance of class using template, don't know how to handle error


I'll try and keep the code short.

I'm trying to make a B inary S earch T ree (BST for short) using templates.

In my add function I'm getting an error and I'm sure I'm misusing templates somehow

All this code is in a .h (header) file because of templates.

EDIT: The const Type & mistake was because of me fiddling around, it was not actually in the code I compile, but from a previous question on Stack overflow

template <typename Type>
class BSTNode {   // Binary Search Tree nodes
  private:
    int key;      // we search by key, no matter what type of data we have
    Type data;
    BSTNode *left;
    BSTNode *right;

  public:
    BSTNode (int, Type);     // key, data
    bool add (int, Type);
};

The add function:

template <typename Type>
bool BSTNode<Type>::add(int newKey, Type newData) {
  if (newKey < this->key) {
    if (left == NULL) {
      this->left = new BSTNode<Type>(int newKey, Type newData);
    }
  } else {
    this->right = new BSTNode<Type>(int newKey, Type newData);
  }
  return false;
}

This is where I get the error:

this->left = new BSTNode<Type>(int newKey, Type newData);

Expected primary expression before int


Solution

  • You are not misuing templates specifically, but you are misusing parameters!

    this->left = new BSTNode<Type>(int newKey, Type newData); 
    

    should look more like

    this->left = new BSTNode<Type>(newKey, newData);