Jump to content

[SOLVED] C : Using unions to implement something like a mixed/generic type


Recommended Posts

At the moment i'm working on something which requires linked lists of various types. It occurs to me that i can make a generic list type with structures and unions. So i might have a structure for an integer list, one for a char list, one for a list of my own type etc and i'll then have a union of them inside another structure along with some flag (probably an enum) to tell me what the list type is.

 

That's all fine and dandy, but i'm not sure what the best way to work with it is. For example, i'll need functions to add to the end of the list but i'd really rather not have to write separate functions for inserting with each type (e.g. i don't want to have add_to_int_list(), add_to_char_list() etc).

 

So to the question: is there anyway to avoid this? Can i somehow pass whatever type i like into a function? On the one hand it seems unlikely, but then what about functions such as printf() which take a variable number of arguments of variable type?

 

Thanks in advance for any input

Link to comment
Share on other sites

In C++ you might could manage it with templates....  Or you could just wrap it in a class and have the .push method do everything.  As far as C goes, you will just have to do a lot of different functions as far as I can tell.  You can of course have a function with the same name as another function and different arguments.

 

 

 

As for how printf does what it does, it does it using va_arg.  (I've used it before to emulate PHP's implementation of pack.)

 

 

Is I understand your question, va_arg will not help you any.

Link to comment
Share on other sites

Have the functions accept data of type void *, which is a pointer to a void.  That's actually C's way of implementing a generic pointer; it can point to any kind of data. Now, you can either use that data directly as is, or you can make a copy of it so the initial code can free the pointer.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.