Hi I am tryna friend a class linkedlist in iterator but idk how to do it with templates
class Iterator{
private:
node<T>* v;
public:
Iterator(node<T>* u){
v = u;
}
T& operator*(){
return v->element;
}
friend class LinkedList;
};
template <class T>
class LinkedList{
public:
node<T>* head;
node<T>* tail;
}
I keep getting an error
doubleLinkedList.cpp: In instantiation of 'class Iterator<int>':
doubleLinkedList.cpp:214:26: required from here
doubleLinkedList.cpp:35:18: error: template argument required for 'class LinkedList'
node<T>* v;
^
I have tried alot of things like i putted a template on top of friend argument but nothing works
CodePudding user response:
If you want to make sure that LinkedList
is only a friend of Iterator
if they share the same T
, then you can forward declare LinkedList
and make the specialization for T
a friend:
template <class T> class LinkedList;
template <class T>
class Iterator{
friend class LinkedList<T>;
};
template <class T> class LinkedList{};
If you want every LinkedList
to be a friend of iterator you could also write
template <class T>
class Iterator{
template <class U> friend class LinkedList; // can't use T here
};
template <class T> class LinkedList{};
But LinkedList<double>
being a friend of Iterator<int>
is probably not what you want. Why not template <class T> friend class LinkedList
whithout forward declaration? That's because nested templates must have different template parameters: one shadowing the other is not allowed.
CodePudding user response:
There are a few issues (see version below to see them applied):
If a template is used (like node) the T must be defined like template <class T>
If you reference something, it must have been declared first. Declared is just the type, like int x;
, class y;
, or <template class T> class z;
The definition -- all the details can come later: int x=7 or the full class definition. This is required for friend
as well.
And, this still gets me sometimes, all classes must end their definition with a ;
template <class T> class node; // this has to be declared or defined first
template <class T>class LinkedList; // this is needed to reference as friend later
template <class T> // this is needed because to pass template args, the class must be templated as well
class Iterator {
private:
node<T>* v;
public:
Iterator(node<T>* u) {
v = u;
}
T& operator*() {
return v->element;
}
friend class LinkedList<T>;
};
template <class T>
class LinkedList{
public:
node<T>* head;
node<T>* tail;
}; // remember the closing semi colon