首页 > 解决方案 > 如何传递类型泛型函数指针?

问题描述

这是我的代码:

 #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

解决方案


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_function某种variant_complex_datum方式获得您想要的东西。

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

C 的变体数据类型库


推荐阅读