Semyon Danilov
Semyon Danilov

Reputation: 1773

ISO C++ forbids declaration of "something" with no type

I am new to template programming in C++, so I decided to start with writing a template list. I get this error on line Node<T> *head; and Node<T> *tail;

Here is my header file (because errors appear only there):

#ifndef LIST_H
#define LIST_H

using namespace std;

template <class T> class List {

public:
    List();
    T get(const int n);
    void add(const T element);
private:
    Node<T> *head;
    Node<T> *tail;
    int size;
};

template <class T> class Node {
public :
    Node();
    T get();
    void setNext(const Node<T> *next);
    Node<T> getNext();
    void setValue(const T value);
private:
   T value;
   Node *next;
};

#endif // LIST_H

Oh, and I tried adding typename before Node<T>, but it gave me expected nested-name-specifier before 'Node'.

Upvotes: 3

Views: 21469

Answers (3)

Pierre Fourgeaud
Pierre Fourgeaud

Reputation: 14510

You have to do a forward declaration of the Node class template before the List because during the List declaration, the compiler doesn't know the Node class:

template <class T> class Node;  // Forward declaration

template <class T> class List {
    // ...
};

template <class T> class Node{
    // ...
};

Or even you can declare your Node class before the List:

template <class T> class Node{
    // ...
};

template <class T> class List {
    // ...
};

By the way, using namespace std; in header is considered a bad practice.

Upvotes: 1

billz
billz

Reputation: 45410

Put your Node definition in front of List or forward declare Node

template <class T> class Node;  // forward declaration for Node

template <class T> class List {    
public:
    List();
    T get(const int n); 
    void add(const T element);
....
};


template <class T> class Node {
public :
....
};

 ....

Upvotes: 5

juanchopanza
juanchopanza

Reputation: 227370

It just means you have to put the Node class template definition before that of List, or forward declare Node before List. The List class template needs to know of the existence of a Node class template.

As an aside, remove the using namespace std, it is bad in general, and very bad in headers.

#ifndef LIST_H
#define LIST_H

template <class T> class Node { /* as before */ };

template <class T> class List { /* as before };

#endif // LIST_H

Upvotes: 2

Related Questions