How to overload functions in C?

一世执手 提交于 2020-11-29 09:49:45

问题


There are lots of posts on this topic, but all of them are not for a complete beginners in C programming.

The thing is that I have three functions:

struct model* createModel_empty(void);
struct model* createModel_single_value(double value);
struct model* createModel_single_value(const double* arr_value);

And I want to just use createModel function in my code which will be substituted with the right implementation.

From my research over the Internet and specifically stack overflow I understood that there are two options to do something like that:

  1. Use macros with _Generics & __ARGS_V__ (no IDEA how to implement)
  2. Use macros with underscored parameters like foo(_1,_2,_3...), but I really don't get what those underscore mean

Please help me with this issue ;(


回答1:


There are lots of post on this topic, but all of them are not for a complete beginners in C programming

Simply because these techniques are not suitable for beginners. For the same reason, you would not find a tutorial for juggling with 7 balls that is aimed at people who cannot juggle with three.

But there is a fairly easy - although bulky - workaround. Wrap the data in a struct.

struct data {
    union {
        const double *p;
        double d;
    } data;
    int type;
};

struct model* createModel_single_value(struct data data) {
    switch(data.type) {
        case 0: return createModel_single_value_double(data.data.d);
        case 1: return createModel_single_value_const_double_ptr(data.data.p);
        default: return NULL;
    }
}

Note that this is a runtime solution and not a compile time which you can achieve with the methods you mentioned. This can make it prone to "interesting behavior" if you're not careful, so I would recommend these precautions:

Use an enum for type, for the sole reason that it's more readable:

enum type { DOUBLE, CONSTDOUBLEPTR };

struct data {
    enum type type;
    ...

And add asserts in the working functions:

struct model* createModel_single_value_double(struct data data) {
    assert(data.type == DOUBLE);

If these really are a performance problem, you can remove them later. Most likely, they are not.

But in general, I would give the advice that you should choose a language that supports the features that you need, and when you have chosen a language, use it as intended. Don't try to shoehorn in stuff that it was not designed for.

Abusing a language can be very fun indeed, and it can also help you get a lot of insights. But these techniques are rarely very useful. Understanding how they work can however often be a great help in debugging.



来源:https://stackoverflow.com/questions/64408323/how-to-overload-functions-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!