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

Asked

Viewed 147 times

5

Taking a stack type data structure 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 another type of data that is not int, should I modify the stack code? Should I create another stack? These alternatives don’t look very good. But in C++ there are templates that arise to solve problems in that same context. So it is possible somehow to simulate the templates of C++ in C?

  • You can do something with macros, but it’s disgusting. I believe that the Gobject library went in that direction, you can analyze the solutions they have adopted to implement a framework with OOP and everything in pure C. But I never liked Gobject.

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, easy to do wrong, and it probably doesn’t pay.

It is always possible to try something creative with macro, ma will be very bad.

If you are using C11 you have the macro _Generic. I don’t think it looks good. And it’s not something that is usually used, I’ve never actually seen a code using, because not all compilers support.

The idea is that if you need this use C++ and be happy.

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

Instead of using a specific type it is used void *, this way the type is generic, what 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 right.

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

Has a basic example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.