这是我的密码:
#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函数是作为函数宏实现的,只有当名称后面跟着()时,这些宏才会展开。
发布于 2019-04-07 19:51:59
在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的库更复杂更全面..。哦是的,给你:
发布于 2019-04-07 19:41:01
_Complex double不是double,sqrt需要双倍,而csqrt需要_Complex双。我没有检查实现,但我想说,您传递的实际上是一个指向sqrt函数的指针,而不是一个数字。
发布于 2019-04-07 22:32:25
我认为代码的行为是这样的,因为tgmath函数是作为函数宏实现的,只有在名称后面跟着()时,这些宏才会展开。
是
有什么办法可以绕过这个吗.?
没有直接绕过它的方法。
使用<tgmath.h>,代码不能提取使用某种类型的对象调用的函数。
您可以使用_Generic编写自己的函数集,但我认为您知道这一点,并试图避免它。
https://stackoverflow.com/questions/55562768
复制相似问题