C具有两种类型的泛型选择
我想使用C具有两种类型的泛型选择,c,generics,c11,C,Generics,C11,我想使用CGeneric selection通过使用两个因子而不是一个因子来推断函数。 假设我有一个C文件: #define draw(X, Y) \ _Generic((X), \ struct circle: draw_circle, \ struct square: draw_square \ )(X, Y) struct circle{}; struct square{}; void draw_circle_with_i
C
Generic selection通过使用两个因子而不是一个因子来推断函数。
假设我有一个C
文件:
#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
应决定函数调用。有什么方法可以做到这一点吗?我手头没有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)
我试过了你的答案,去掉了一些逗号,结果成功了。这比我想象的要简单得多。我已经编辑了您的答案以使其正确。您可能应该改为使用那些结构参数
const struct type*
。