I want to write a function in C that will accept any type of data types like int, char, float, o开发者_如何学Pythonr any other data type and do some operation on them. As this is possible in C++, is it possible in C?
It wouldn't be pretty. Take a look at this page for an example. Lots of macro usage.
About the only thing you can do in C is macros, the poor cousins of templates. For example:
#define max(a, b) ((a) < (b) ? (b) : (a))
Note that this has a huge problem... the macro arguments are evaluated more than once. For example:
max(i+=1, i);
expands to:
((i+=1) < (i) ? (i+=1) : (i));
And the result of that expression could be all kinds of interesting things on various compilers.
So, macros are really a poor substitute for templates. You can make 'functions' that are type agnostic with them. But they come with a number of hurdles and pitfalls that make them practically useless for anything really significant. They are also rather 'hairy' and make your code a lot harder to understand than templates do.
The max
example I just gave may not seem that hairy (though the doubled evaluation of arguments is certainly a surprising and difficult to deal with thing), but here is an example of declaring something like a templated vector type with macros, and it is obviously hairy.
You can create and accept a union
, or you can take a pointer to the data using the generic void*
. C doesn't, however, support templating as in C++.
Yes, it can be achieved by using macros. See http://www.flipcode.com/archives/Faking_Templates_In_C.shtml
You can arrange a cheat using ...
e.g. with varargs
function
I guess it must be a void pointer
void *p;
Just typecast and use it. what you have asked is the limitation of c thats why it is introduced in c++
After reading your comment i guess you need an argument to send the datatype of variable
func( void *p, int ) \\ second argument must be a datatype use sizeof to find the datatype
精彩评论