gpt4 book ai didi

c - C 中函数 typedef 的前向声明

转载 作者:行者123 更新时间:2023-12-04 12:09:07 24 4
gpt4 key购买 nike

我一直怀疑以前有人问过这个问题,但我没有找到......
假设我有一个函数 A 的 typedef,它接受一个指向带有 typedef B 的函数的指针,后者又接受一个 typedef A 的函数。如果其中一个是结构,我知道我将如何处理前向声明,但对于函数我不知道语法。有吗?
我希望能够做到:

typedef void (*function_A_t)(function_B_t f_B);
typedef void (*function_B_t)(function_A_t f_A);
任何提示?更好的是,引用?顺便说一句,这实际上只是发生在我身上,但我能够以另一种方式修复它,尽管这实际上会更顺畅(更好的解耦,下一个人搞砸的机会更少),如果可能的话。

最佳答案

您可以利用以下事实来做到这一点:C 指定没有参数的函数声明意味着它需要不确定数量的参数。
所以你可以这样做:

typedef void (*function_A_t)(void (*)());
typedef void (*function_B_t)(function_A_t f_A);
这允许以下编译:
void A(function_B_t b)
{
b(A);
}

void B(function_A_t a)
{
a(B);
}

int main()
{
function_A_t a = A;
function_B_t b = B;
a(B);
b(A);
return 0;
}
C standard 的第 6.7.6.3p15 节关于函数类型的兼容性,声明如下:

For two function types to be compatible, both shall specifycompatible return types. Moreover, the parameter type lists, ifboth are present, shall agree in the number of parameters andin use of the ellipsis terminator; corresponding parametersshall have compatible types. If one type has a parameter type listand the other type is specified by a function declarator that isnot part of a function definition and that contains an emptyidentifier list, the parameter list shall not have an ellipsisterminator and the type of each parameter shall be compatible withthe type that results from the application of the defaultargument promotions. If one type has a parameter type list and theother type is specified by a function definition that contains a(possibly empty) identifier list, both shall agree in the numberof parameters, and the type of each prototype parameter shallbe compatible with the type that results from the applicationof the default argument promotions to the type of thecorresponding identifier. (In the determination of typecompatibility and of a composite type, each parameter declaredwith function or array type is taken as having the adjusted typeand each parameter declared with qualified type is taken as having theunqualified version of its declared type.)


上面粗体部分指定 void (*)()兼容 void (*)(function_B_t)

关于c - C 中函数 typedef 的前向声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68187814/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com