p.chives
p.chives

Reputation: 125

Overloading cout with template class

I'm rebuilding my class as a template and I'm having trouble with overloading cout (working without the template). gcc throws this error when I try to compile:

error: ‘LinkedList’ is not a type
ostream& operator <<(ostream&, LinkedList&);

The code for the LinkedList.h class is:

template <typename value_type>

class LinkedList
{
public:
LinkedList();

~LinkedList();

void addToHead(const typename node<value_type>::value_type& entry);
void addToTail(const typename node<value_type>::value_type& entry);
void set_current(node<value_type>* entry);
void remove(string);
void remove_from_head();
void remove_from_tail();
void list_clear();

int list_length();
int count(string name);
double calcAverage();
bool search(string);
node<value_type> * get_head();
node<value_type> * get_tail();
node<value_type> * get_current();

LinkedList& operator+=(LinkedList&);

private:
node<value_type>* head;
node<value_type>* tail;
node<value_type>* current;
};
template <typename value_type>
ostream& operator <<(ostream&, LinkedList&);

I assume this has something to do with templates and that this part of the code is outside the scope of the class but different combinations of typedef and just seemed to cause more errors.

Upvotes: 3

Views: 315

Answers (2)

Petok Lorand
Petok Lorand

Reputation: 973

Indeed LinkedList is not a type there, it is a template.

You can create a type out of the template by instantiating it, substituting it's template parameters with types.

template <typename value_type>
ostream& operator <<(ostream&, const LinkedList<value_type>&);

Edit: As suggested by @Scheff the linked listed should also be const, because the operator<< should never change it.

Upvotes: 7

Marius Bancila
Marius Bancila

Reputation: 16338

That is because LinkedList is not a type indeed. LinkedList<int> or LinkedList<std::string> is a type. While LinkedList<value_type> is a type template used to build actual types.

What you need to do is to specify the template parameter as follows:

template <typename value_type>
ostream& operator <<(ostream&, LinkedList<value_type>&);

Upvotes: 2

Related Questions