如何使用_Generic 修饰名称?
How can I use a decorated name with _Generic?
我正在编写一个库,让用户可以像这样修饰函数名称:
#ifndef DECORATE // Define this before including if you want to change the names.
#define DECORATE(name) lib_##name
#endif
我现在如何使用 _Generic
创建一个通用函数 foo
如下所示:
#define DECORATE(foo)(x) \
_Generic((x), \
int: DECORATE(fooi), \
float: DECORATE(foof) \
)(x)
这当然给我一个错误,因为我不能两次定义DECORATE
宏。有没有办法修饰通用函数的名称或者这是不可能的?
您需要为您的宏指定两个不同的名称,以便一个可以使用另一个。此外,在使用 _Generic
的情况下,两个参数都需要位于一组由空格分隔的括号中。
#ifndef DECORATEX
#define DECORATEX(name) lib_##name
#endif
#define DECORATE(foo,x) \
_Generic((x), \
int: DECORATEX(foo##i), \
float: DECORATEX(foo##f) \
)(x)
void lib_abci(int x)
{
printf("in abci, x=%d\n", x);
}
void lib_abcf(float x)
{
printf("in abcf, x=%f\n", x);
}
int main()
{
int a=3;
float b=4.5;
DECORATE(abc,a);
DECORATE(abc,b);
return 0;
}
输出:
in abci, x=3
in abcf, x=4.500000
我正在编写一个库,让用户可以像这样修饰函数名称:
#ifndef DECORATE // Define this before including if you want to change the names.
#define DECORATE(name) lib_##name
#endif
我现在如何使用 _Generic
创建一个通用函数 foo
如下所示:
#define DECORATE(foo)(x) \
_Generic((x), \
int: DECORATE(fooi), \
float: DECORATE(foof) \
)(x)
这当然给我一个错误,因为我不能两次定义DECORATE
宏。有没有办法修饰通用函数的名称或者这是不可能的?
您需要为您的宏指定两个不同的名称,以便一个可以使用另一个。此外,在使用 _Generic
的情况下,两个参数都需要位于一组由空格分隔的括号中。
#ifndef DECORATEX
#define DECORATEX(name) lib_##name
#endif
#define DECORATE(foo,x) \
_Generic((x), \
int: DECORATEX(foo##i), \
float: DECORATEX(foo##f) \
)(x)
void lib_abci(int x)
{
printf("in abci, x=%d\n", x);
}
void lib_abcf(float x)
{
printf("in abcf, x=%f\n", x);
}
int main()
{
int a=3;
float b=4.5;
DECORATE(abc,a);
DECORATE(abc,b);
return 0;
}
输出:
in abci, x=3
in abcf, x=4.500000