C通用选择有两种类型

时间:2016-04-17 03:53:01

标签: c generics c11

我想使用#define draw(X, Y) \ _Generic((X), \ struct circle: draw_circle, \ struct square: draw_square \ )(X, Y) struct circle{}; struct square{}; void draw_circle_with_int(struct circle a, int i){} void draw_circle_with_double(struct circle a, double d){} void draw_square_with_int(struct square a, int i){} void draw_sqaure_with_double(struct square a, double d){} int main(void) { struct circle c; /* draw(c, 3); */ // `draw_circle_with_int` /* draw(a, 3.5); */ // `draw_circle_with_double` struct square s; /* draw(s, 5); */ // `draw_square_with_int` /* draw(s, 5.5); */ // `draw_square_with_double` } 通用选择通过使用两个因子而不是一个因子来推断函数。 我们说我有draw(X, Y)个文件:

X

Y中,split以及-应决定函数调用。有没有办法做到这一点?

1 个答案:

答案 0 :(得分:4)

我没有C11编译器方便对不起所以我无法测试它,但也许你可以试试这个:

#define draw(X, Y) \
        _Generic((X), \
            struct circle: _Generic((Y), \
                int: draw_circle_with_int, \
                double: draw_circle_with_double ), \
            struct square: _Generic((Y), \
                int: draw_square_with_int, \
                double: draw_square_with_double ) \
        )(X, Y)