hi everyone,
Can I make a single function accept different pairs of structures
that will make the function process the data in similar way...?
Thank you
hi everyone,
Can I make a single function accept different pairs of structures
that will make the function process the data in similar way...?
Thank you
No. (How would the function know which kind of thing it has?)
Yes.
Say your function works with either 2 int's as parameters, or two strings. So your function declaration would be:
int function(int, n1, int n2, char * ptrToString1, char* ptrToString2)
Inside the function, you have the logic so your function knows if it's sent -99 or some weird & impossible ints, that it should work with the strings, on that call.
And just the reverse when you want the function to work on the ints, and not the strings.
Or you can just use a flag. flag == 1, work with the int's. flag = 0, work with the strings.
You could use a void pointer for the function to accept whatever you want. But you will have to provide also what kind of structs you are passing (as a parameter) in order to dereference the void* correctly. But this usually isn't very helpful...
Well, yeah. That will work. Or do:
rather than having a function that combines both.Code:int res = flag ? funInt(n1, n2) : funStr(str1,str2);
One function won't do you any good. You won't be able to access the structs with a similar way. Even if you use void*. There is no way doing this:
even if both str1 and str2 have a member val.Code:void fun(struct str1 *s1, struct str2 *s2, int value) { s = theStructIWant(); s->value = value; }
You could pass them with a void* but this will give an error:
You would need to use polymorphism. In C++ you could use virtual functions, for example:Code:void fun(void *s, int value) { s->value = value; }
Code:void fun(base *s, int value) { s->setValue(s); }
oh ok....Thank you for your response.
It would of course help a whole lot of you showed us what kind of structures they are - for example, if they are similar enough and if there is a some way you can identify which struct it is, you could make a union of all the structures, and then fish out the relevant data. [Or a struct with a union inside it, so that you can pass the type along with the struct inside the union].
But generally, if you have different data structures, it's usually because they contain different things, and that usually means that they are processed differently.
It's all dependant on how similar the structures are, and how you can tell which one it is.
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.