gpt4 book ai didi

c - 如何传递泛型函数指针?

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:51 26 4
gpt4 key购买 nike

这是我的代码:

 #include <stdio.h>
#include <tgmath.h>

double complex execmathfunc(double complex val, double complex (*mathfunc)(double complex))
{
return mathfunc(val);
}

int main()
{
double complex val = -1;
val = execmathfunc(val, sqrt); //if I put csqrt here it works
printf("%.1f+%.1fi", creal(val), cimag(val));
return 0;
}

如果我使用 csqrt,这段代码可以正常工作,并且会按预期输出 0.0+1.0i,但是如果我使用常规 sqrt(将我寄希望于 tgmath.h 的泛型函​​数),它为实部输出垃圾值,为虚部输出 0。有什么方法可以解决这个问题,还是我需要坚持使用 csqrt 和所有其他复杂函数作为参数传递它们?

我相信代码会以这种方式运行,因为 tgmath 函数是作为函数宏实现的,并且只有在名称后跟 () 时才会扩展。

最佳答案

C 中没有类型泛型函数指针这样的东西。

但是,您可以为不同的相关类型创建一个指针结构,例如


typedef enum {
USE_FLOAT = 0,
USE_DOUBLE = 1,
// USE_LONG_DOUBLE = 2 // maybe you have this one as well
} complex_component_type_selector;

typedef struct {
union {
float complex (*float_)(float complex);
double complex(*double_)(double complex);
} function_ptr;
complex_component_type_selector component_type;
} variant_function;

typedef union {
union {
float complex float_;
double complex double_
} datum;
complex_component_type_selector component_type;
} variant_complex_datum;

然后您可以传递 variant_complex_functionvariant_complex_datum 来获得您想要的东西。

... 现在,我的建议是对一些 variants 的实现有点粗鲁和半途而废。 .我确信 C 的库更复杂、更全面……哦,是的,给你:

Variant datatype library for C

关于c - 如何传递泛型函数指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55562768/

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