Prak
Prak

Reputation: 1069

Is it possible to achieve temeplatization in C as it is possible in C++

I want to write a function in C that will accept any type of data types like int, char, float, or any other data type and do some operation on them. As this is possible in C++, is it possible in C?

Upvotes: 2

Views: 165

Answers (6)

niko
niko

Reputation: 9393

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

Upvotes: 0

Omnifarious
Omnifarious

Reputation: 56038

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.

Upvotes: 1

Neel Basu
Neel Basu

Reputation: 12904

You can arrange a cheat using ... e.g. with varargs function

Upvotes: 0

John W
John W

Reputation: 610

Yes, it can be achieved by using macros. See http://www.flipcode.com/archives/Faking_Templates_In_C.shtml

Upvotes: 0

Zeenobit
Zeenobit

Reputation: 5194

It wouldn't be pretty. Take a look at this page for an example. Lots of macro usage.

Upvotes: 9

Emil Vikstr&#246;m
Emil Vikstr&#246;m

Reputation: 91912

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++.

Upvotes: 0

Related Questions