在我的 C 项目中,有一个由另一位同事创建的结构,其中包含一些函数指针:
struct tools {
int (*tool_a) (int, int, int);
...
};
我无权更改此结构和相关文件。
现在我正在使用结构进行编码。
我必须定义一个函数,其返回类型和参数列表必须与 tools.tool_a
相同。
这意味着我的函数必须如下所示:
int my_func(int, int, int);
问题是struct变了很多,尤其是返回类型,比如int
今天换成了size_t
,所以我得改很多代码.
我知道 C++ 中的 decltype
可以帮助我,所以我只想知道 C 是否有等效的东西?
我想我可以使用宏,但我不知道如何,我什至不知道它是否可能。
真实案例
我正在用 C 为 linux-kernel 开发一些测试工具。
我公司的其他团队有很多版本的自定义内核。由于历史原因,有的使用int
,有的使用size_t
或ssize_t
等。
现在当我编码时,我必须这样做:
// int my_func(int a, int b, int c)
size_t my_func(int a, int b, int c)
// ssize_t my_func(int a, int b, int c)
{}
struct tools my_tool = {
.tool_a = my_func;
}
我必须继续评论和取消评论...
最佳答案
理智的解决方案是强制执行 typedef
。如果那是不可能的,并且该函数可能具有的替代类型的数量有限(看起来就是这种情况),您可以使用 C11 _Generic
编写一些东西。
与其使用名为 my_func
的单个函数,不如创建多个具有不同名称的函数。根据返回类型为它们的名称添加前缀。然后有一个宏,它会根据传递的类型重新定向到适当的函数。
例子:
#include <stdio.h>
/*** the struct that cannot be changed ***/
struct tools {
int (*tool_a) (int, int, int);
};
/*** any number of functions with different types ***/
int int_my_func(int a, int b, int c)
{
puts(__func__);
}
size_t size_t_my_func(int a, int b, int c)
{
puts(__func__);
}
/*** macro to select the appropriate function based on type ***/
#define my_func_typeof(type) \
_Generic( (type), \
int(*)(int,int,int) : int_my_func, \
size_t(*)(int,int,int) : size_t_my_func)
/*** caller code ***/
int main (void)
{
struct tools my_tool = {
.tool_a = my_func_typeof( (struct tools){0}.tool_a )
};
my_tool.tool_a(1,2,3);
}
在这里,我使用复合文字 (struct tools){0}.tool_a
创建了一个与 tool_a
类型相同的虚拟对象,然后将其传递给选择适当功能的宏。如果不支持该类型,则会出现编译器错误,因为找不到匹配的 _Generic 关联。
关于c++ - C 等效于 C++ decltype,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48182676/