Note that there are some explanatory texts on larger screens.

plurals
  1. POFunction pointers working as closures in C++
    primarykey
    data
    text
    <p>Is there a way in C++ to effectively create a closure which will be a function pointer? I am using the Gnu Scientific Library and I have to create a <a href="http://www.network-theory.co.uk/docs/gslref/Providingthefunctiontosolve.html" rel="nofollow noreferrer">gsl_function</a>. This function needs to effectively "close" a couple of parameters available when I create it. Is there a nice trick to create a closure so that I don't have to pass all of them as params in the gsl_function structure? If not, should I just pass in a pointer to an array containing these parameters?</p> <p><strong>EDIT</strong> I have tried to use boost::bind like this:</p> <pre><code>#include &lt;gsl/gsl_integration.h&gt; #include &lt;boost/bind.hpp&gt; #include "bondpricecalculator.h" #include "functions.h" double integrand (double xi, double t, double x, void * p) { Functions *functions = (Functions *) p; double vx = functions-&gt;v(x); return functions-&gt;rho0(x)*exp(vx * xi - 0.5 * vx * vx * t); } double BondPriceCalculator::value(double t, double T, double xi) { gsl_integration_workspace * w = gsl_integration_workspace_alloc (10000); gsl_function F; F.function = &amp;boost::bind(integrand, xi, t, _1, _2); F.params = &amp;functions; double integral_t; double integral_T; double error; int res = gsl_integration_qags(&amp;F, T, 1e+14, 0, 1e-7, 10000, w, &amp;integral_T, &amp;error); if(res) { throw "Error intgrating"; } int res = gsl_integration_qags(&amp;F, T, 1e+14, 0, 1e-7, 10000, w, &amp;integral_t, &amp;error); if(res) { throw "Error intgrating"; } return integral_T/integral_t; } </code></pre> <p>but I got the following error message:</p> <pre><code>/home/ga/svn/PhD/inflation/cpp/ioi/bondpricecalculator.cpp:20: error: cannot convert ‘boost::_bi::bind_t&lt;double, double (*)(double, double, double, void*), boost::_bi::list4&lt;boost::_bi::value&lt;double&gt;, boost::_bi::value&lt;double&gt;, boost::arg&lt;1&gt;, boost::arg&lt;2&gt; &gt; &gt;*’ to ‘double (*)(double, void*)’ in assignment </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload