c - 如何传递类型泛型函数指针?
问题描述
这是我的代码:
#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_function
某种variant_complex_datum
方式获得您想要的东西。
...现在,我的建议是一些变体的实现有点粗鲁和半途而废。我确信有更复杂和全面的 C 库......哦,是的,给你:
推荐阅读
- javascript - 将html属性添加到字符串
- javascript - 如何在两天内设置 flatpickr 时间选择器?
- python - XBRL 模块无法识别
- javascript - 如何在 redux-saga 中以有限的并发和合理的取消实现批处理任务?
- swift - 为什么 Xcode 认为这是可选的?
- python - 根据不均匀的时间戳索引插值Column数据
- machine-learning - 基于用户评论的 NLP 文本分类
- javascript - 为什么作为函数参数的内联解构不能按预期工作
- javascript - 替换()函数失败,应该用文本框条目替换标题
- azure - 未找到版本“GeneralPurpose”的默认服务级别目标