4

Навеяно этим вопросом.
Вот есть рабочий код:

#include <stdio.h>

struct Point
{
    int x;
    int y;
};

#define CHECK_TYPE(X) _Generic((X),    \ 
    int: "int",                        \
    double: "double",                  \
    struct Point: "struct Point"       \
)

int main(void)
{   
    struct Point point;
    printf("%s\n", CHECK_TYPE(1));
    printf("%s\n", CHECK_TYPE(1.1));
    printf("%s\n", CHECK_TYPE(point));

    return 0;
}

Вывод:

int
double
struct Point

Теперь немного изменим его:

#include <stdio.h>

struct Point
{
    int x;
    int y;
};

#define F(X) _Generic((X),    \
    int: int_F(X),            \
    double: double_F(X),      \
    struct Point: point_F(X)  \
)

void int_F(int v)
{
    printf("Hello int!\n");
}

void double_F(double v)
{
    printf("Hello double!\n");
}

void point_F(struct Point p)
{
    printf("Hello Point!\n");
}

int main(void) {
    struct Point point;
    F(1);
    F(1.1);
    F(point);

    return 0;
}

При попытке компиляции получаем следующие ошибки:

prog.c: In function ‘main’:
prog.c:32:4: error: incompatible type for argument 1 of ‘point_F’
F(1);
^
prog.c:12:27: note: in definition of macro ‘F’
struct Point: point_F(X) \
^
prog.c:25:27: note: expected ‘struct Point’ but argument is of type ‘int’
void point_F(struct Point p)
~~~~~~~~~~~~~^
prog.c:33:4: error: incompatible type for argument 1 of ‘point_F’
F(1.1);
^~~
prog.c:12:27: note: in definition of macro ‘F’
struct Point: point_F(X) \
^
prog.c:25:27: note: expected ‘struct Point’ but argument is of type ‘double’
void point_F(struct Point p)
~~~~~~~~~~~~~^
prog.c:34:4: error: incompatible type for argument 1 of ‘int_F’
F(point);
^~~~~
prog.c:10:16: note: in definition of macro ‘F’
int: int_F(X), \
^
prog.c:15:16: note: expected ‘int’ but argument is of type ‘struct Point’
void int_F(int v)
~~~~^

Но стоит лишь убрать из _Generic часть со struct Point и всё начинает работать:

#include <stdio.h>

#define F(X) _Generic((X),    \
    int: int_F(X),            \
    double: double_F(X)       \
)

void int_F(int v)
{
    printf("Hello int!\n");
}

void double_F(double v)
{
    printf("Hello double!\n");
}

int main(void)
{
    F(1);
    F(1.1);

    return 0;
}

Вывод:

Hello int!
Hello double!

Вопрос: В чём ошибка? Почему в первом случае _Generic спокойно обрабатывет struct Point, а во втором случае нет?

1 ответ 1

3

Ответ навеялся читая :

https://stackoverflow.com/questions/53590497/using-generic-type-in-c-for-function-overloading-in-a-nested-structure

Синтаксис у вас неправильный.

# define F( X ) _Generic((X),    \
    int : int_F ,            \
    double : double_F ,      \
    struct Point : point_F  )(X)

так пашет.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.