-
Passing data type
So i'm trying to write a class with all the functions same as vector. I know i can use the vector template but i just want to give myself a little challenge.
Ok, vector takes classes, but my i intent to make it take only data type (char, string, int, float....). Because i will need "push" function to add stuff into the array, so i started like this:
Code:
struct link
{
void* dataType;
link* next;
};
Then i start out with a class:
Code:
class myVector
{
private:
link* base;
public:
myVector(){ base = NULL; }
void Push(void* data)
{
link* var = new link;
var->dataType = data;
var->next = base;
base = var;
}
void Display()
{
link* var = base;
while(var != 0)
{
cout<<var->dataType<<endl;
var = var->next;
}
}
};
So this way, i can only display the memory of the data type (or whatever it is) when i push in. If i want to actually display the variable, i have to use
Code:
(variable type*)var->dataType;
So is there anyway i can convert from void* to whatever data type the users want when they declare the class. like this:
Code:
public:
void* variable_need_to_convert;
myVector( user's data type)
{
//convert the variable_need_to_convert into this data type
}
//Then
void Display()
{
cout<<(converted data type) data<<endl;
}
-
If you want to make a container like vector (Although yours looks more like a linked list), use templates.
your class would look something like
Code:
template <typename T>
class mycontainer
{
T data;
mycontainer<T> *next;
public:
// Accessor functions
};
another advantage to using templates is that it doesn't matter what data types you use, the class treats them all the same.
Edit : When creating a class like this (or any templated class), I strongly recommend you start out with a POD type such as an int. Templates always bring their own problems into the mix, so if you're creating a generic linked list such as std::list, make one which is specific to one type, and deal with any bugs which result from that first. When that is working, convert it to work with any type.