Linklist and Templates

hi All

I Have been Searching the Internet For A while Now And could Not Find A Good Answer.

My Question Is Can We Make A Link List Of Which`s node Only Contains One Data Element e.g int float etc etc.... but the link list can contain different node types.... like this where [] is one node

[(int=12) (next->) ] - [(float=45.6) (next->)] - [(char='c') (next=NULL)]

I tried
tempalate <class T>
class node
{
public:
T data;
Node < T > * Next;
};

but this Logic Wont Work ...
Cause Node<float> `s address cant be saved into Node *.or ViseVersa Or anyother type...

i would Prefer a Solution With templates Used


CAn It Be DOne Where am I going Wrong
Can you rephrase the question? I don't get what you are trying to do here.

Anyway expressions like int=12 or float=45.6 and char='c' are not valid in C++. They are types and probable you need variables of these types assigned those values.
I think you can go with your current design(with Node<> template). Below is how to get your goal.

class IntNode : public Node<int>
{
blah blah;
};

Then using objects of IntNode to make a list for int type only.

Do same thing for float:

class FloatNode : public Node<float>
{ blah blah; };

Last edited on
What I Am Trying to Do Is Posted Below But with a better logic i.e templates

#include <iostream.h>
#include <typeinfo>
#include <string.h>
#include <windows.h>
#include <stdio.h>


class Node
{
public:

char * c;
int * i;
double * f;

Node * next;

void valuesetter()
{
cout<<" Enter Data the type of Data You Want To Enter "<<endl;
cout<<" 1.Int 2.Float 3.Char : ";

int input;
cin>>input;
cout<<endl;
if(input==1)
{
cout<<" Enter The Data You Want To Put ";
cin>>input;
i=new int;
*i=input;
}

if(input==2)
{
double a;
cout<<" Enter The Data You Want To Put ";
cin>>a;
f=new double;
*f=a;
}
if(input==3)
{
char a;
cout<<" Enter The Data You Want To Put ";
cin>>a;
c=new char;
*c=a;
}
}

void displaydata()
{
if(c!=NULL)
cout<<*c;
if(i!=NULL)
cout<<*i;
if(f!=NULL)
cout<<*f;

}



Node()
{
next=NULL;
c=NULL;
i=NULL;
f=NULL;
}
};


class List
{
public:
Node * first;
Node * last;

List()
{
first=last=NULL;
}

void create()
{
Node *temp=NULL;

temp=new Node;
temp->valuesetter();

if(first==NULL)
{
first=temp;
last=temp;
}
else
{
last->next=temp;
last=temp;
}

cout<<" Enter More Y/N";
char c;
cin>>c;
if(c=='y')
create();
else
return;

}

void print()
{
Node *temp=NULL;
temp=first;

while(temp!=NULL)
{
temp->displaydata();
cout<<" ";
temp=temp->next;
}

}
};


void main()
{
List a;
a.create();

cout<<endl<<endl;

a.print();
}
Topic archived. No new replies allowed.