Avinash
Avinash

Reputation: 13277

C++ generic container with linked list

I want to design a generic container for use with linked lists (for example). I tried using void* as an element but this fails when I provide the following.

list.insert(5);
list.insert("Hello");

If I allocate the member on the heap and pass the address it works, but how can I handle the case of using stack variables in the example above?

Upvotes: 0

Views: 606

Answers (4)

Lundin
Lundin

Reputation: 215350

You need to add the size in bytes somehow.

int x = 5;
insert (&x, sizeof(int));
insert ("Hello", 6);

etc.

The insert method could then for example look like this:

void insert (void* data, size_t size)
{
  node_t node = malloc ...

  node.data = malloc ...
  node.size = size;

  memcpy(node.data, data, size);
}

Upvotes: 0

satnhak
satnhak

Reputation: 9891

Personally I would use boost::any for this.

Upvotes: 4

Anders
Anders

Reputation: 290

... could simply try to overload the insert function...

List::insert( int i ){}
List::insert( char* i ){}

etc....

Upvotes: 1

flolo
flolo

Reputation: 15526

If you really want a generic container, you have no choice but to create a dummy object containing the scalar value (OMG-why do I have to think of java?) and insert that. You could add special insert_int, insert_char, ... methods how do the copying on their own. This way you had also no trouble with literals and stack variables.

Upvotes: 0

Related Questions