具有两种类型的 C 泛型选择
C Generic Selection with two types
我想使用 C
通用选择通过使用两个而不是一个来推断函数。
假设我有这个 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)
我想使用 C
通用选择通过使用两个而不是一个来推断函数。
假设我有这个 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)