On 3/31/2018 4:19 PM, Chris M. Thomasson wrote:
> So here is what I quickly came up with, keep in mind that I never really
> used _Generic before except with tgmath.h:
> _________________________________
> #include <stdio.h>
>
>
> struct foo_0
> {
> int blah0;
> };
[...]
> void foo_0(struct foo_0* self, int a, int b)
> {
> printf("foo_0(%p, blah0: %u, %u, %u)\n",
> (void*)self, self->blah0, a, b);
[...]
> _________________________________
>
>
> As you can see, this code allows me to call the right implementation of
> foo, as foo_0 or foo_1 depending on the type of the first parameter.
> Now, can you see anything terribly wrong here? Is this Kosher?
Well, try to look past the fact that I am using the wrong type in
printf! %u instead of %d... Here, let me quickly fix this example code
by changing the types in foo_N structs to unsigned int:
_________________________________
#include <stdio.h>
struct foo_0
{
unsigned int blah0;
};
struct foo_1
{
unsigned int blah0;
unsigned int blah1;
};
void foo_0(struct foo_0* self, int a, int b)
{
printf("foo_0(%p, blah0: %u, %u, %u)\n",
(void*)self, self->blah0, a, b);
}
void foo_1(struct foo_1* self, int a, int b)
{
printf("foo_1(%p, blah0: %u, blah1: %u, %u, %u)\n",
(void*)self, self->blah0, self->blah1, a, b);
}
#define foo(a, ...) \
(_Generic((a), \
struct foo_0*: foo_0, \
struct foo_1*: foo_1 \
)((a), __VA_ARGS__))
int main(void)
{
struct foo_0 f0 = { 1 };
struct foo_1 f1 = { 2, 3 };
foo(&f0, 4, 5); // Calls foo_0
foo(&f1, 4, 5); // Calls foo_1
return 0;
}
_________________________________
Sorry about that non-sense. Well, that it what you get when the code is
quickly typed out.
;^o