Aug 3, 2010 at 11:22am UTC
Hi,
this code was running fine on g++2.3 but getting template mismatch id error on g++
4.2. could anyone point out me reason.
using namespace std;
template<class T>
class node
{
public:
T data;
node *next;
};
template<class T>
class link
{
public:
node<T> *first;
link();
void add_node(T data);
friend ostream& operator<< <T> (ostream &o ,link<T> &link_lst);
};
template<class T>
link<T>::link()
{
first =NULL;
}
//Create node in link list
template<class T>
void link<T>::add_node(T data)
{
node<T> *last;
node<T> *p =new node<T>;
p->data =data;
p->next =NULL;
if(first==NULL)
first=p;
else
{
last=first;
while(last->next!=NULL)
last =last->next;
last->next =p;
}
}
template<class T>
ostream& operator<<(ostream &o,link<T> &link_list)
{
node<T> *last =link_list.first;
while(last !=NULL)
o<<" ---->"<<last->data<<endl;
last=last->next;
}
}
int main()
{
link<int>a;
a.add_node(3);
a.add_node(4);
cout<<a;
}
Aug 3, 2010 at 2:11pm UTC
Please use code tags.
What is the exact error message?
Doesn't line 8ish need to be node<T>* next
?
Aug 3, 2010 at 3:14pm UTC
Sorry for providing incomplete info.. I tried with new program also and got following error. it also same issue which is compilable
in g++ 2.3 but getting error in 4.2
Error :
circular.cpp: In instantiation of ‘circular<int>’:
circular.cpp:69: instantiated from here
circular.cpp:22: error: template-id ‘operator<< <int>’ for ‘std::ostream& operator<<(std::ostream&, circular<int>&)’ does not match any template declaration
Program:
/ *
* Circular link list
* */
#include<iostream>
using namespace std;
template<class T>
class node
{
public:
T data;
node<T> *next;
};
template<class T>
class circular
{
public:
circular();
void add_node(T data);
node<T> *first;
friend ostream& operator<< <T>(ostream& o,circular<T>& list);
};
template<class T>
circular<T>::circular()
{
first =NULL;
}
template<class T>
void circular<T>::add_node(T data)
{
node<T> *last;
node<T> *p =new node<T>;
p->data =data;
if(first==NULL)
first=p;
else
{
last =first;
while(last->next!=first)
last=last->next;
p->next;
last->next=p;
first=p;
}
}
template<class T>
ostream& operator << (ostream& o,circular<T>& list)
{
node<T> *last =list.first;
while(last->next!=last)
{
o<<" last--->data "<<last->data;
last =last->next;
}
}
int main()
{
circular<int> c;
for(int i=0;i<5;i++)
c.add_node(i);
cout<<c;
return 0;
}
Last edited on Aug 3, 2010 at 3:15pm UTC
Aug 3, 2010 at 5:11pm UTC
Try something like (line 22):
1 2
template <typename T2>
friend ostream& operator <<(ostream& o,circular<T2>& list);
Last edited on Aug 3, 2010 at 5:12pm UTC
Aug 3, 2010 at 6:33pm UTC
thx it is working but could i know the reason why it was not working.....
Aug 3, 2010 at 6:38pm UTC
It looks like the syntax for template member functions has changed over the years (gcc 2.3 is very old).