C equivalent to C++ decltype
C equivalent to C++ decltype
在我的C项目中,有一个由另一位同事创建的结构,包含一些函数指针:
struct tools {
int (*tool_a) (int, int, int);
...
};
我无权更改此结构和相关文件。
现在我正在使用结构进行编码。
我必须定义一个函数,其返回类型和参数列表必须与tools.tool_a
相同。
这意味着我的函数必须如下所示:
int my_func(int, int, int);
问题是结构变化很大,尤其是返回类型,例如int
今天被size_t
替换,所以我必须对代码进行大量更改。
我知道decltype
C++可以帮助我,所以我只想知道 C 是否有等效的东西?
我想我可能会使用宏,但我不知道怎么做,我什至不知道这是否可能。
真实案例
我正在用C为linux内核开发一些测试工具,有许多
版本的自定义内核来自我公司的其他组。由于历史原因,他们中的一些人使用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关联。
好吧,这不是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
};
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- C++decltype和圆括号-为什么
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 如何从"decltype()"获取函数参数的数量<funtion>?
- Confusion: decltype vs std::function
- decltype(1, t) 应该是 l 值引用吗?(编译器不同意)
- 是否可以在不使用 decltype 的情况下推断先前定义的 extern 变量的类型
- 无效 f(int) 的模板和 decltype
- c++ 11 带有 decltype 的尾随返回类型无法按预期工作
- 我可以使用 decltype() 或其他东西通过指针获取真实类型吗?
- decltype:使用指针访问类的静态成员
- decltype() 不适用于正在编译的类模板
- 在部分模板专用化中使用 decltype
- 非静态成员函数的 decltype 格式不正确吗?
- 是否可以使用单个定义定义函数的常量和常规版本?(使用模板,自动,decltype等)
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- "decltype(&ordenary_func)"和"decltype"(ordenary_func)之间的区别
- 指向具有 decltype 的函数的指针向量
- About std::unique_prt() and decltype()
- 来自 decltype 的意外输出类型