C equivalent to C++ decltype

C equivalent to C++ decltype

本文关键字:decltype C++ to equivalent      更新时间:2023-10-16

在我的C项目中,有一个由另一位同事创建的结构,包含一些函数指针:

struct tools {  
int (*tool_a) (int, int, int);
...
};

我无权更改此结构和相关文件。

现在我正在使用结构进行编码。
我必须定义一个函数,其返回类型和参数列表必须与tools.tool_a相同。
这意味着我的函数必须如下所示:

int my_func(int, int, int);

问题是结构变化很大,尤其是返回类型,例如int今天被size_t替换,所以我必须对代码进行大量更改。

我知道decltypeC++可以帮助我,所以我只想知道 C 是否有等效的东西?

我想我可能会使用宏,但我不知道怎么做,我什至不知道这是否可能。

真实案例

我正在用C为linux内核开发一些测试工具,有许多
版本的自定义内核来自我公司的其他组。由于历史原因,他们中的一些人使用int,另一些使用size_tssize_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关联。

好吧,这不是decltype但是如果你能说服你的同事使用类型别名,你可以进行静态类型检查。

如果可以说服您的同事这样做:

typedef int tool_a_prototype(int, int, int);
struct tools {  
tool_a_prototype *tool_a;
};

然后你可以像这样声明你的函数:

tool_a_prototype my_tool_a;
int my_tool_a(int a, int b, int c) {
//Whatever
}

你友好的编译器会告诉你是否存在原型不匹配。

问题是结构变化很大,尤其是返回 类型,例如int今天被size_t替换,所以我必须 经常更改我的代码。

我知道 decltype in C++可以帮助我,所以我只想知道 C 是否 有等价物吗?

如果你愿意使用非标准的gcc扩展,你可以使用typeof

struct tools {  
int (*tool_a) (int, int, int);
};
typedef typeof( ((struct tools*)NULL)->tool_a ) tool_a_type;
typedef typeof( ((tool_a_type)NULL)(0,0,0) ) tool_a_return_type;
tool_a_return_type my_func(int x, int y, int z)
{
}
struct tools my_tool = {
.tool_a = my_func
};