Richard Rasmussen
Richard Rasmussen

Reputation: 69

output overload using template

So I'm trying to overload the output operator using templates, but I keep running into two errors. They are:

Error C2988 unrecognizable template declaration/definition

and

Error C2143 syntax error: missing ',' before '<'

template <typename E> class SLinkedList; //forward declaration

template <typename E>
ostream& operator<< (ostream& out, const SLinkedList<E>& v); //forward declaration

template <typename E> 
class SLinkedList {
public:

template <typename E>
friend ostream& operator<< <E>(ostream& out, const SLinkedList<E>& v);
};

template <typename E>
ostream& operator <<(ostream& out, E const SLinkedLst<E>& v) {
while (v->next != NULL) {
    out << v->elem;
    v->next;
}

return out;
}

Upvotes: 1

Views: 89

Answers (2)

Mykola
Mykola

Reputation: 3363

Try that instead

template <typename E> 
class SLinkedList {
public:
template <typename T>
friend std::ostream& operator << (std::ostream& out, const SLinkedList<T>& v);
};

template <typename E>
std::ostream& operator << (std::ostream& out, const SLinkedList<E>& v) {
while (v->next != NULL) {
    out << v->elem;
    v->next;
}

  return out;
}

Upvotes: 0

NathanOliver
NathanOliver

Reputation: 180500

<E> is not needed in

friend ostream& operator<< <E>(ostream& out, const SLinkedList<E>& v);

Just get rid of it and it should compile.

You are also missing a ; at the end of you class. In C++ a class and struct declaration must end with a ;

You have an extra E in

ostream& operator <<(ostream& out, E const SLinkedLst<E>& v) {
                                   ^ what is this doing here?

You are also missing a ; at then end of

v->next

You are also using the same template name in

template <typename E> 
class SLinkedList {
public:

template <typename E>
friend ostream& operator<< <E>(ostream& out, const SLinkedList<E>& v);
};

Which E is the function referring too? You will need to change it to some other name.

Upvotes: 1

Related Questions