C ++ Template Class

I am trying to create a template for my university project. I wrote the following code:

#ifndef _LinkedList_H_ #define _LinkedList_H_ #include "Link.h" #include <ostream> template <class L>//error one class LinkedList { private: Link<L> *pm_head; Link<L> * pm_tail; int m_numOfElements; Link<L>* FindLink(L * dataToFind); public: LinkedList(); ~LinkedList(); int GetNumOfElements(){return m_numOfElements;} bool Add( L * data); L *FindData(L * data); template <class L> friend ostream & operator<<(ostream& os,const LinkedList<L> listToprint);//error two L* GetDataOnTop(); bool RemoveFromHead(); L* Remove(L * toRemove); 

this temple uses a link class cluster

 #ifndef _Link_H_ #define _Link_H_ template <class T>//error 3 class Link { private: T* m_data; Link* m_next; Link* m_prev; public: Link(T* data); ~Link(void); bool Link::operator ==(const Link& other)const; /*getters*/ Link* GetNext()const {return m_next;} Link* GetPrev()const {return m_prev;} T* GetData()const {return m_data;} //setters void SetNext(Link* next) {m_next = next;} void SetPrev(Link* prev) {m_prev = prev;} void SetData(T* data) {m_data = data;} }; error one: shadows template parm `class L' error two:declaration of `class L' error three: shadows template parm `class T' 

I do not understand what the problem is. I really can use your help thanks :)

+7
source share
2 answers

These error messages really belong together:

 a.cc:41: error: declaration of 'class L' a.cc:26: error: shadows template parm 'class L' 

This means that on line 41 you enter the pattern parameter L; in my copy it refers to

 template <class L> friend ostream & operator<<(ostream& os, const LinkedList<L> listToprint);//error two 

And this declaration obscures the template parameter on line 26:

 template <class L>//error one class LinkedList 

You need to rename the template parameter in the friend declaration.

Change Relevant language specification - 14.6.1 / 7

The template parameter should not be updated within its competence (including nested areas). The template parameter must not have the same name as the template name.

When you reference L in const LinkedList<L> listToprint , it is unclear whether you have a L value of a friend or an L class. Therefore write

 template <class L1> friend ostream & operator<<(ostream& os, const LinkedList<L1> listToprint); 
+14
source

Just uninstall

  template <class L> 

from a member function declaration friend .

You also need to replace using ostream with std::ostream if you don't have using namespace std somewhere in your code.

Otherwise, the code looks fine.

+3
source

All Articles