【发布时间】:2018-04-14 09:29:36
【问题描述】:
我尝试实现 _Generic 宏,它可以采用任何数据类型并对其进行处理,此示例工作正常,但是使用 2 个通用宏,我如何仅使用一个具有 char* int 和 double 的 Generic 来实现它?
#include <stdio.h>
#include <stdlib.h>
#define puts(x) _Generic((x), \
char*: _puts((void*) x, "str"), \
int: _puts((void*) x, "int") \
)
#define putsd(x) _Generic((x),\
double: _puts((void*)to_s(x), "float") \
)
char*
to_s(double x)
{
char* str = (char *)malloc(1502);
sprintf(str, "%lf", x);
free(str);
return str;
}
void _puts(void* d, const char* type)
{
if (strcmp(type, "int") == 0){
printf("%d\n", d);
} else if (strcmp(type, "float") == 0){
double res;
sscanf(d, "%lf", &res);
printf("%lf\n", res);
} else {
printf("%s\n", d);
}
}
int main(void) {
puts("String");
puts(1230);
putsd(13.37);
return 0;
}
另外,当我尝试跟随时,我得到一个错误“'to_s' puts("String"); 的参数 1 的类型不兼容:
#include <stdio.h>
#include <stdlib.h>
#define puts(x) \
_Generic((x), \
char*: _puts((void*) x, "str"), \
int: _puts((void*) x, "int"), \
double : _puts((void *)to_s(x), "float") \
)
char *to_s(double x) {
char *str = (char *)malloc(1502);
sprintf(str, "%lf", x);
free(str);
return str;
}
void _puts(void *d, const char *type) {
if (strcmp(type, "int") == 0) {
printf("%d\n", d);
} else if (type == "float") {
double res;
sscanf(d, "%lf", &res);
printf("%lf\n", res);
} else {
printf("%s\n", d);
}
}
int main(void) {
puts("String");
puts(1230);
puts(13.37);
return 0;
}
【问题讨论】: