-
Working with void*
Hey there; I've been working on a really simple class for a void pointer linked list. I'm looking for a way to deal with having to convert to void* and then back to whatever type I'm using. For example:
My class:
Code:
struct GSLLNODE {
void* dat;
GSLLNODE* next;
};
class GSLL {
private:
GSLLNODE *root;
public:
GSLL() {root = new GSLLNODE; root->next = 0;}
void Next(void* dat);
void* GetNext();
};
void GSLL::Next(void* dat) {
GSLLNODE *n = new GSLLNODE;
GSLLNODE *cur = root;
n->dat = dat;
n->next = 0;
while(cur->next)
cur = cur->next;
cur->next = n;
}
void* GSLL::GetNext() {
if(!root->next)
return 0;
root = root->next;
return root->dat;
}
Code:
int main() {
GSLL gg;
int f = 0;
gg.Next((void*)++f);
gg.Next((void*)++f);
gg.Next((void*)++f);
gg.Next((void*)++f);
gg.Next((void*)++f);
gg.Next((void*)++f);
f = (int)gg.GetNext();
while(f) {
std::cout << f;
f = (int)gg.GetNext();
}
std::cin >> f;
return 0;
}
I suppose I'm looking for some sort of auto-interface to cast the void pointer automatically? It'd help cut the amount of neccesary coding drastically.
-
Have you considered the use of templates?
-
Typically when using void pointers, it is left to the programmer to know what type they are. And as a side note, in your GSLL::Next function, you're passing in an integer as a void pointer -- I doubt you will be able to use the same code for a linked list of floats/doubles.
C++ offers a few things you can use to "auto-interface to cast the void pointer automatically". As laserlight said, a Template would probably be easiest here. Another way would be, instead of using void pointers, have it as a list of a certain interface. Anything you want to be in the list would have to implement that interface in order for the list to use it. This wouldn't be practical for lists of primitive types, but if you're going to be having lists of objects.