Is it possible to "simulate" C ++ Templates in C?

4

Taking a data structure of type stack with array for example :

typedef struct stack_s {
    int top;
    int item[STACK_MAX_SIZE];
} stack_t;

Doubt appears when for some reason I want to use a stack with a data type other than int , should I change the stack code? Should I create another stack? These alternatives do not look very good. But in C ++ there are the templates that come up to solve problems in that same context. So is it possible to somehow simulate the templates of C ++ in C?

    
asked by anonymous 15.10.2016 / 18:04

1 answer

3

Not exactly.

You can even create a tool to read the generic code and generate the concrete for each type. It's hard, hard work, easy to do wrong, and probably does not pay.

It's always possible to try something creative with macro, but it will be pretty bad.

If you are using C11 you have the _Generic macro. I do not think it looks good. And it's not something that's usually used, actually I've never seen a code using it. The idea is that if you need this use C ++ and be happy.

A practice that is often used in such cases is polymorphism, but it loses type security and there is a small loss of performance.

Instead of using a specific type, use void * , so the type is generic, whatever is used will be accepted. In compensation you can send anything you accept, unless you create a logic trying to prevent the error, which is not simple to do right in C. In general the custom is to trust that the programmer will use certain.

C is a weak typing language with low type security. One of the reasons for creating C ++ is to solve this problem.

You have a basic example .

    
15.10.2016 / 18:32