how to avoid static member function when using gsl with c++(将gsl与c ++一起使用时如何避免静态成员函数)
问题描述
我想在 C++ 类中使用 GSL,而不将成员函数声明为 static
.这样做的原因是因为我不太了解它们,而且我不确定线程安全性.从我读到的内容来看,std::function
可能是一个解决方案,但我不确定如何使用它.
I would like to use GSL within a c++ class without declaring member functions as static
. The reason for this is because I don't know them too well and I'm not sure about thread safety. From what I read, std::function
might be a solution but I'm not sure how to use it.
我的问题归结为如何删除 g
声明中的 static
?
My question comes down to how can I remove static
in declaration of g
?
更新 (1):
我尝试将 gsl_monte_function G = { &g, 3, 0 };
更改为 gsl_monte_function G = { bind(&A::g, this,_1,_2,_3), 3, 0 };
但没用
I tried changing gsl_monte_function G = { &g, 3, 0 };
to gsl_monte_function G = { bind(&A::g, this,_1,_2,_3), 3, 0 };
but it didn't work
更新 (2):我尝试使用 将 std::function 分配给成员函数 但它没有也不能工作.
Update (2): I tried using assigning std::function to a member function but it didn't work either.
更新 (3)最后我写了一个非成员函数:
Update (3) in the end I wrote a non-member function:
它有效,但这是一个混乱的解决方案,因为我需要编写一个辅助函数.使用 lambda、函数和绑定,应该有一种方法可以让类中的所有内容都合乎逻辑.
It worked but it's a messy solution because I needed to write a helper function. With lambdas,function and bind, there should be a way to have everything logical within the class.
推荐答案
您可以使用以下代码轻松包装成员函数(这是众所周知的解决方案)
You can easily wrap member functions using the following code (which is a well known solution)
然后你可以使用 std::bind 将成员函数包装在一个 std::function 中.示例:
Then you can use std::bind to wrap the member function in a std::function. Example:
但是,在将成员函数包装在 gsl 集成例程中之前,您应该了解 std::function 的性能损失.参见 模板与 std::function .为避免这种性能下降(这对您来说可能重要也可能不重要),您应该使用如下所示的模板
However, you should be aware about the performance penalties of std::function before wrapping member functions inside gsl integration routine. See template vs std::function . To avoid this performance hit (which may or may not be critical for you), you should use templates as shown below
在这种情况下,要调用成员函数,您需要以下内容
In this case, to call a member function you need the following
PS:链接 模板与 std::function 解释了编译器通常具有比 std::function 更容易优化模板(如果您的代码正在进行大量数值计算,这对性能至关重要).所以即使在第二个例子中的解决方法看起来更麻烦,我更喜欢模板而不是 std::function.
PS: the link template vs std::function explains that compiler usually has an easier time optimizing templates than std::function (which is critical for performance if your code is doing heavy numerical calculation). So even tough the workaround in the second example seems more cumbersome, I would prefer templates than std::function.
这篇关于将gsl与c ++一起使用时如何避免静态成员函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!