Reputation: 3
I have read most posts with the same problem, but I haven't found my problem in those solutions.
I want to wirte a simple linked List with generic content:
But I get the written error "variable or field >>insert<< as void declared" and this for each method except the main.
I hope you can help me, Thanks
#include<iostream>
#include<string>
//EDIT:#include"liste.t" this is waste from a former test
using namespace std;
template <typename T>
struct Element{
T value;
Element *next;
Element(T v, Element *n) : value(v), next(n)
{ }
};
template <typename T>
void insert(Element, T, int (*eq)(T,T));
template <typename T>
void remove(Element, T, int (*eq)(T,T));
void print(Element);
template <>
int equal<string>(T, T);
template <typename T>
int equal(T, T);
int main(){
int (*eq)(int,int) = equal;
Element* head=NULL;
insert(head, 2, eq);
insert(head, 5, eq);
insert(head, 1, eq);
print(head);
remove(head, 2, eq);
print(head);
}
template <typename T>
void insert(Element* &rp, T v, int (*eq)(T, T)){
if(rp!=NULL){
if(eq(rp->value, v)>=0){
rp = new Element(v, rp);
}else{
insert(rp->next, v, eq)
}
}else{
rp = new Element(v, NULL);
}
}
template <typename T>
void remove(Element * &rp, T v, int (*eq)(T, T)){
if(rp!=NULL){
if(eq(rp->value, v)==0){//v
Element *tmp = rp;
rp=rp->next;
delete tmp;
remove(rp,v, eq);
}else{
remove(rp->next, v, eq);
}
}
}
void print(Element *p){
while(p){
cout<<p->value << " ";
p=p->next;
}
cout << endl;
}
template <>
int equal<string>(T a, T b){
int min=0;
if(length(a)<length(b)){
min = length(a);
}else{
min=length(b);
}
for(int i=0; i< min; i++){
if(a[i]<b[i])
return -1;
if(a[i]>b[i])
return 1;
}
return 0;
}
template <typename T>
int equal(T a, T b){
if(a<b)
return -1;
if(a>b)
return 1;
return 0;
}
Upvotes: 0
Views: 1110
Reputation: 618
NOTE: You should probably use std::list
or std::forward_list
instead of rolling out your own container.
In the function declarations you'll encounter a compile error using Element without a template parameter (this is probably the error you are asking about):
template <typename T>
void insert(Element, T, int (*eq)(T,T));
^
This should use Element<T>
instead and should also take in a pointer to the Element.
template <typename T>
void insert(Element<T>*, T, int (*eq)(T,T));
The print
function also needs to be a template:
template <typename T>
void print(Element<T> *p)
It also appears that you are trying to specialize equals for strings using template specialization. The declaration should read:
template <>
int equal<string>(string, string);
because T is not declared in this context.
I need to stress again that you should really, really consider using std::list
or std::forward_list
instead of rolling out your own container. There is no need to reinvent the wheel.
Upvotes: 1