Katia Abela
Katia Abela

Reputation: 269

Member access into incomplete type error: Templatized struct C++

Pretty new to C++ and having my first try at templates. I created a struct, treeNode, having left, right and parent pointers. I want the tree to be able to store multiple data types and hence am using templates. Whenever I try create an instance of the struct in the .cpp file, and then use it to access the left/right pointers of the tree I get this error: Member access into incomplete type struct 'treeNode'. Any idea on what I'm missing?

Here is the code in the .h file(struct definition):

template <class T>
struct treeNode {
    node<T> *l;
    node<T> *r;
    node<T> *p;   
};

Here is my attempt in the .cpp file:

#include "RedBlack.h"

struct treeNode* t;

Tree::Tree() {
    t->l = NULL;
}

Upvotes: 0

Views: 2867

Answers (3)

Jack
Jack

Reputation: 133679

  • First of all since you are declaring a recursive struct, members should have the same type of the struct itself.
  • Second thing: templates are not like generics in Java. They don't provide a real available implementation until you replace the type variable with a real type, so you must always use them specialized or by keeping some type variables still unchosen in another template context (eg. the Tree class below)

Since you want to have a generic tree, then the Tree class should be generic too:

template <class T>
struct node {
  node<T> *l;
  node<T> *r;
  node<T> *p;
};

template <class T>
class Tree
{
  private:
    node<T> *root;

  public:
    Tree() : root(nullptr) { }
};

Tree<int> *tree = new Tree<int>();

Upvotes: 2

Vlad from Moscow
Vlad from Moscow

Reputation: 311186

Apart from that you did not set a template argument it seems you made a typo. Instead of

template <class T>
struct treeNode {
    node<T> *l;
    node<T> *r;
    node<T> *p;   
};

should be

template <class T>
struct treeNode {
    treeNode<T> *l;
    treeNodeT> *r;
    treeNode<T> *p;   
};

Upvotes: 0

John Dibling
John Dibling

Reputation: 101506

A treeNode is nothing -- literally not a thing -- without it's template parameters.

You must do:

treeNode <int> * t;

Or something similar.

Upvotes: 0

Related Questions