gpt4 book ai didi

c++ - 从另一个函数创建一个函数

转载 作者:可可西里 更新时间:2023-11-01 18:31:25 26 4
gpt4 key购买 nike

除了一般情况,我还有一个非常具体的例子:在 GSL(GNU 科学图书馆)中,使用的主要函数类型(为了执行积分、求根...)是 gsl_function ,它有一个属性 function ,其类型是 double(*)(double, void *)

假设我想从 double a_squared(double a) {return a*a}; 创建一个 gsl_functiona__squared 的类型是 double(*)(double) 我想创建一个 convert 函数接受参数 (double( *)(double) f) 并返回满足 convert(f)(double a, NULL) 的 double(*)(double, void *) 类型的对象== f(a)

但经过一些研究,我似乎无法在我的 convert 函数中定义另一个函数。如何进行?

最佳答案

将原始函数指针传递给 GSL API 的需要极大地限制了您的选择 - 您不能使用任何基于 std::function 的东西,因为无法从std::function(这排除了使用捕获的 lambda,这将提供一个简洁的解决方案)。

考虑到这些限制,这里有一个可能的解决方案,即使用静态包装器类。您也可以将此类的内容放在命名空间中,但使用该类至少提供了一些封装的表象。

typedef double gsl_function_type(double, void*);  // typedef to make things a bit more readable...

// static class to wrap single-parameter function in GSL-compatible interface
// this really just serves as a namespace - there are no non-static members,
// but using a class lets us keep the details private
class Convert
{
Convert() = delete; // don't allow construction of this class

// pointer to the function to be invoked
static double (*m_target)(double);

// this is the function we'll actually pass to GSL - it has the required signature
static double target(double x, void*) {
return m_target(x); // invoke the currently wrapped function
}

public:
// here's your "convert" function
static gsl_function_type* convert(double (*fn)(double)) {
m_target = fn;
return ⌖
}
};

这里有一个实例:http://coliru.stacked-crooked.com/a/8accb5db47a0c51d

关于c++ - 从另一个函数创建一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33350046/

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