Is there a way to do something like this : ?
void set(void* data, void *value, t_flags type)
{
if (type & INT)
*(int*)data = *(int*)value;
if (type & UINT)
(...)
}
int i;
set(&i, 42, INT);
My set function works but I don't know how to call it with number, char '', or string "".
Edit : I've forgot the last argument, but the problem come from the 42 argument.
A few things. First, since you're using a
void*
(which is appropriate) forvalue
, you need to pass avoid*
as your second argument, instead of a constant. This will work to copy one variable to the next, but there are more efficient ways.Second, note that for passing a string, you need to pass a pointer to a char pointer, and the char* will get set by the function. (It's up to you whether it's a "soft copy" or "hard copy" - i.e. whether the pointer points to the same place in memory or to another copy of the same string. You said you had
set
implemented, so I'm guessing you already have it the way you want.You haven't included your t_flags enum, so I guessed appropriate values.
The bigger question for me is why you would want to do this, especially since in your flag you already need to know the type. It's much cleaner (and has much better type checking) to simply do:
I'm assuming this is just for learning about functions, or it's massively simplified for a complex issue. Either way, that's how you do it.