SNpn
SNpn

Reputation: 2207

error: expected a type, got 'struct' c++

I got a class:

template <typename T> 
class btree {

  public:
    btree(size_t maxNodeElems);
    ~btree() {}

    struct node {  
      list <T> elements;
      node *lvl;
    };

  private:
    size_t maxNodeElems;
    node*  root;   

};

template <typename T>
btree<T>::btree(size_t maxNodeElems) {
  if (maxNodeElems > 0) maxNodeElems = maxNodeElems;
  root = new node;
  root->lvl = new node[maxNodeElems+1];
}

template <typename T>
pair <typename btree<T>::iterator, bool> btree <T>::insert (const T& elem) {
  pair <btree<T>::node, bool> start;
  start = addElement (elem, *root);
  pair <typename btree<T>::iterator, bool> final;
  return final;
}

template <typename T>
pair <btree<T>::node, bool> btree<T>::addElement (const T& e, btree<T>::node*& n) {

  n->elements.push_back(e);
  return make_pair(*n, true);
}

the error that it keeps giving is:

error:   expected a type, got 'btree::node'
error: invalid type in declaration before ';' token
At global scope:
error: type/value mismatch at argument 1 in template parameter list for 'template<class _T1, class _T2> struct std::pair'
error:   expected a type, got 'btree::node'

This seems to be happening on the line:

pair <btree<T>::node, bool> btree<T>::addElement (const T& e, btree<T>::node*& n) {

I'm calling it the same way in the header, and I don't understand why its saying I'm not giving it the right type. Can someone explain this to me?

Upvotes: 0

Views: 4103

Answers (3)

MichalR
MichalR

Reputation: 263

You need to use typename to tell the compiler that dependent name defines a type:

template <typename T>
pair <typename btree<T>::node, bool> btree<T>::addElement (const T& e, typename btree<T>::node*& n)

Upvotes: 4

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361792

It is a very common error.

Use typename as:

pair<typename btree<T>::node, bool> 
     ^^^^^^^^

It is because node is a dependent type, as it depends on the template parameter T.

Upvotes: 4

Kerrek SB
Kerrek SB

Reputation: 477640

You have to say:

pair <typename btree<T>::node, bool>
      ^^^^^^^^

This is because in the template setting, btree<T> is unresolved and btree<T>::node is a dependent name, which you need to disambiguate.

Upvotes: 7

Related Questions