您的BrentsFindRoot 采用无状态函数指针。
你的 lambda 有状态。
这些不兼容。无论是概念上还是句法上。
BrentsFindRoot( double (*f)(void const*, double), void const*, double a, double b, double tol )
如果您添加状态并希望它保持纯 C 函数,这就是签名将如何更改。然后传递一个 lambda 在概念上是可行的,但语法很尴尬。如果您不介意根查找器中的 C++:
BrentsFindRoot( std::function<double(double)> f, double a, double b, double tol )
或者,您可以通过表/全局状态技巧将状态转换为无状态函数指针。您还可以通过获取和存储与 a 等效的内容作为编译时参数来使 lambda 无状态。
但只需使用std::function 版本。
如果BrentsFindRoot 是一个只有头部的函数,你可以使用一个模板
template<class F>
void BrentsFindRoot( F f, double, double, double );
最后一个选择是找到或写一个function_view 类型;通过避免存储,这可能比std::function 更有效。
union function_state {
void* pvoid;
void(* pfvoid)();
function_state(void* p=nullptr):pvoid(p) {}
template<class R, class...Args>
function_state(R(*pf)(Args...)):pfvoid(reinterpret_cast<void(*)()>(pf)) {}
};
template<class Sig>
struct function_view;
template<class R, class...Args>
struct function_view<R(Args...)> {
function_state state;
R(*pf)(function_state, Args&&...args) = nullptr;
R operator()(Args...args)const {
return pf(state, std::forward<Args>(args)...);
}
function_view(function_view const&)=default;
function_view& operator=(function_view const&)=default;
explicit operator bool() const{ return pf; }
function_view( R(*f)(Args...) ):
state(f),
pf([](function_state s, Args&&...args)->R{
return reinterpret_cast<R(*)(Args...)>(s.pfvoid)( std::forward<Args>(args)... );
})
{}
template<class F, std::convertible_to<R> FR=std::invoke_result_t< F, Args... >>
requires (!std::is_same_v<R,void>)
function_view( F&& f ):
state((void*)std::addressof(f)),
pf([](function_state s, Args&&...args)->R{
return (*static_cast<F*>(s.pvoid))( std::forward<Args>(args)... );
})
{}
template<class F>
requires (std::is_same_v<R, void>)
function_view( F&& f ):
state((void*)std::addressof(f)),
pf([](function_state s, Args&&...args)->void{
(*static_cast<F*>(s.pvoid))( std::forward<Args>(args)... );
})
{}
template<std::convertible_to<R> R0, std::constructible_from<Args>...As>
requires (!std::is_same_v<R,void>)
function_view( R0(*f)(As...) ):
state(f),
pf([](function_state s, Args&&...args)->R{
return reinterpret_cast<R0(*)(As...)>(s.pfvoid)( std::forward<Args>(args)... );
})
{}
template<class R0, std::constructible_from<Args>...As>
requires (std::is_same_v<R, void>)
function_view( R0(*f)(As...) ):
state(f),
pf([](function_state s, Args&&...args)->void{
reinterpret_cast<R0(*)(As...)>(s.pfvoid)( std::forward<Args>(args)... );
})
{}
};
但这可能不是你想写的东西。