问题
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:
- Use macros with
_Generics
&__ARGS_V__
(no IDEA how to implement) - 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