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.
My question comes down to how can I remove static in declaration of g?
#include<iostream>
#include <functional>
#include <stdlib.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_monte.h>
#include <gsl/gsl_monte_plain.h>
#include <gsl/gsl_monte_miser.h>
#include <gsl/gsl_monte_vegas.h>
using namespace std;
class A {
public:
static double g (double *k, size_t dim, void *params)
{
double A = 1.0 / (M_PI * M_PI * M_PI);
return A / (1.0 - cos (k[0]) * cos (k[1]) * cos (k[2]));
}
double result() {
double res, err;
double xl[3] = { 0, 0, 0 };
double xu[3] = { M_PI, M_PI, M_PI };
const gsl_rng_type *T;
gsl_rng *r;
////// the following 3 lines didn't work ///////
//function<double(A,double*, size_t, void*)> fg;
//fg = &A::g;
//gsl_monte_function G = { &fg, 3, 0 };
gsl_monte_function G = { &g, 3, 0 };
size_t calls = 500000;
gsl_rng_env_setup ();
T = gsl_rng_default;
r = gsl_rng_alloc (T);
{
gsl_monte_plain_state *s = gsl_monte_plain_alloc (3);
gsl_monte_plain_integrate (&G, xl, xu, 3, calls, r, s, &res, &err);
gsl_monte_plain_free (s);
}
gsl_rng_free (r);
return res;
}
};
main() {
A a;
cout <<"gsl mc result is " << a.result() <<"\n";
}
Update (1):
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
Update (2):
I tried using assigning std::function to a member function but it didn't work either.
Update (3)
in the end I wrote a non-member function:
double gmf (double *k, size_t dim, void *params) {
auto *mf = static_cast<A*>(params);
return abs(mf->g(k,dim,params));
//return 1.0;
};
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)
class gsl_function_pp : public gsl_function
{
public:
gsl_function_pp(std::function<double(double)> const& func) : _func(func){
function=&gsl_function_pp::invoke;
params=this;
}
private:
std::function<double(double)> _func;
static double invoke(double x, void *params) {
return static_cast<gsl_function_pp*>(params)->_func(x);
}
};
Then you can use std::bind to wrap the member function in a std::function. Example:
gsl_function_pp Fp( std::bind(&Class::member_function, &(*this), std::placeholders::_1) );
gsl_function *F = static_cast<gsl_function*>(&Fp);
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
template< typename F >
class gsl_function_pp : public gsl_function {
public:
gsl_function_pp(const F& func) : _func(func) {
function = &gsl_function_pp::invoke;
params=this;
}
private:
const F& _func;
static double invoke(double x, void *params) {
return static_cast<gsl_function_pp*>(params)->_func(x);
}
};
In this case, to call a member function you need the following
Class* ptr2 = this;
auto ptr = [=](double x)->double{return ptr2->foo(x);};
gsl_function_pp<decltype(ptr)> Fp(ptr);
gsl_function *F = static_cast<gsl_function*>(&Fp);
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 takes a C-type functions “int (*)(char,float)” rather than C++-type “int (Fred::*)(char,float)”. To convert a member function to the C-type function, you need to add static.
see Is the type of “pointer-to-member-function” different from “pointer-to-function”?
Why are you worried about the static function in this case?
Variables and/or objects declared in a static function are not shared between different threads unless they are static themselves (which in your case they are not).
Is your code failing to do something?
Sorry, but what you're trying to do doesn't make any sense. Whatever thread safety issues you're worried about, they won't be solved by adding or removing the static keyword.
The only reason why you would make g non-static would be if an instance of A was somehow required for g's operation. And g's current implementation doesn't require such an instance.
Note you can also make g a global function, without the static keyword. There would be no visible difference in your case. However it's better style in your case to have g in the class which makes use of it, as a static function.
Also, Here is some related material about pointers to (static/non-static) member functions.
Related
I have a library taking a callback of type
double *(double)
Now I want to pass a couple of callbacks which are parameterized on another parameter. More precisely I have a function with signature
double f(double, int)
Now I would like to write something like
for(int parameter: {...some values(known at compile time)...})
{
//register callback x mapsto f(x,parameter)
}
I cannot wrap the callback in a lambda because it would be capturing, so it is not convertible to a function pointer. Also as I understand it, bind objects cannot be converted to function pointers (although I am not really sure why) so I cannot bind the parameter.
Does anybody know how this can be done?
EDIT: I would like a solution using the compilers template engine to generate those functions for me.
Also if this is helpfull, I have c++17 and I would also be open to using libraries such as boost hana if necessary.
You need some for of storage to keep the bound value, a raw function pointer can't do that unless you create functions using macros at compile time. (or in a far future using reflection+meta classes) Doing this at run time won't work.
What you can use is std::bind and then for example store std::function instances.
#include <vector>
#include <functional>
double function(double, int);
void register_all() {
using namespace std::placeholders;
// values to bind
std::vector<int> v = { 1, 4, 6, 8 };
// our callback registry
std::vector<std::function<double(double)>> funcs;
// registration
for (auto i : v) {
funcs.emplace_back(std::bind(function, _1, i));
}
//call
for (auto &f : funcs) {
f(1.0);
}
}
If you can't change the callback type to std::function or something similar the only way is to register a single callback doing further calls. i.e.
double my_callback(double d) {
for (int i : whatever) {
f(d, i);
}
}
// ... somewhere else
register_callback(my_callback);
Side note:
A good C callback API would allow passing a void* through, which can be given for extra callback specific information, which could be used to carry the extra data. However the simple function pointer is too limited for anything else.
Edit:
If you know all your (potential) values at compile time you could use a template to wrap:
#include <vector>
double f(double d, int i);
template<int i>
double f_wrapper(double d) {
return f(d, i);
}
int main() {
std::vector<double(*)(double)> funcs;
funcs.push_back(&f_wrapper<0>);
funcs.push_back(&f_wrapper<1>);
funcs.push_back(&f_wrapper<2>);
//call
double r = .0;
for (auto &f : funcs) {
r += f(1.0);
}
}
With some more variadic template magic:
#include <vector>
double f(double d, int i);
template<int i>
double f_wrapper(double d) {
return f(d, i);
}
template<int... id>
void register_cbs(std::vector<double(*)(double)>& funcs) {
(funcs.push_back(&f_wrapper<id>), ...);
}
int main() {
// register
std::vector<double(*)(double)> funcs;
register_cbs<1,2,5,10>(funcs);
//call
double r = .0;
for (auto &f : funcs) {
r += f(1.0);
}
}
But again the values have to be known at compile time.
I am trying to pass a custom lambda to a function that expects a function pointer (more precisely the zero function in Brent library).
The idea is that I would create the lambda once with the parameters and then it would be evaluated at several values x inside this function.
I have tried the steps in this thread with no success and I am getting an error of no known conversion for argument 4 from ‘Function {aka std::function<double(double)>}’ to ‘double (*)(double)’. As far as I understand the compiler does not know how to cast from those 2 types.
Is there a workaround around this error? It would be better if no modifications had to be made to the library and it could be solved within my program. Here is a snippet of code to show the problem.
# include <functional>
# include "brent.hpp"
using namespace brent;
typedef std::function<double(double)> Function;
Function function_builder (double a, double b)
{
return [a,b](double x) {
return ( a * x + b );
};
}
int main ( )
{
Function func = function_builder ( 2.0, -1.0 );
double z = zero (0, 1, 0.001, func ); //func should be a function pointer of type double (*)(double)
return 0;
}
In your case, your lambda function has state - the captured a, b variables. There is no way to convert a stateful lambda to a pointer to function, but...
The Brent library does not expect a pointer to function. The zero function is declared as:
double zero ( double a, double b, double t, func_base& f )
and has an overload defined as:
// This is the overload you asked about, but....
double zero ( double a, double b, double t, double f ( double x ) ){
func_wrapper foo(f);
return zero(a, b, t, foo);
}
But you should use the first variant for your needs, which expects:
class func_base{
public:
virtual double operator() (double) = 0;
};
which is good news, since you simply have to derive from func_base, and put a lambda in there:
template <class Lambda>
class FunctionWithState : public func_base, public Lambda {
public:
FunctionWithState(const Lambda & lambda): Lambda(lambda) {}
double operator()(double x) override
{ return Lambda::operator()(x); }
};
template<class Lambda>
auto function_builder_base (Lambda lambda)
{
return FunctionWithState<decltype(lambda)>(lambda);
}
auto function_builder(double a, double b)
{
return function_builder_base([a,b](double x) {
return ( a * x + b );
});
}
The implementation details are a bit ugly, but the usage is reasonable:
main ( )
{
// func must be "auto" because the type depends on lambda, whose type is unknown.
auto func = function_builder ( 2.0, -1.0 );
double z = zero (0, 1, 0.001, func );
return 0;
}
Of course, it is possible to get rid of the lambda function altogether, and to manage state inside a non-templated object. But on the other hand, inheriting from lambda makes it easy to define many other function builders such as:
auto function_builder3(double a, double b, double c)
{
return function_builder_base([a,b,c](double x) {
return ( a*x*x + b*x + c );
});
}
In fact, you can use function_builder_base directly everywhere, eliminating the need for a function_builder middleman.
You won't have much luck without ugly hack (like using a global object of sorts) of passing a std::function<double(double)> to a double(*)(double). The key difference is that function pointer genuinely only abstract stateless functions while std::function<double(double)> or lambda functions with non-empty capture contain state.
Specifically for the Brent library mentioned there is, however, a way! The library doesn't really take function pointer but travels in terms of func_base objects. You can get one of these with a simple adapter:
struct brent_fun: func_base {
std::function<double(double)> fun;
template <typename Fun>
explicit brent_fun(Fun&& fun): fun(std::move(fun)) {}
double operator()(double value) override { return this->fun(value); }
};
Abstract
I have a class that stores a optimization problem and runs a solver on that problem.
If the solver fails I want to consider a sub-problem and solve using the same solver (and class).
Introduction
An optimization problem is essencially a lot of (mathematical) functions. The problem functions are defined outside the class, but the sub-problem functions are defined inside the class, so they have different types (e.g. void (*) and void (MyClass::*).
At first I thought that I could cast the member function to the non-member pointer-to-function type, but I found out that I cannot. So I'm searching for some other way.
Example Code
An example code to simulate my issue:
#include <iostream>
using namespace std;
typedef void (*ftype) (int, double);
// Suppose foo is from another file. Can't change the definition
void foo (int n, double x) {
cout << "foo: " << n*x << endl;
}
class TheClass {
private:
double value;
ftype m_function;
void print (int n, double x) {
m_function(size*n, value*x);
}
public:
static int size;
TheClass () : value(1.2), m_function(0) { size++; }
void set_function (ftype p) { m_function = p; }
void call_function() {
if (m_function) m_function(size, value);
}
void call_ok_function() {
TheClass ok_class;
ok_class.set_function(foo);
ok_class.call_function();
}
void call_nasty_function() {
TheClass nasty_class;
// nasty_class.set_function(print);
// nasty_class.set_function(&TheClass::print);
nasty_class.call_function();
}
};
int TheClass::size = 0;
int main () {
TheClass one_class;
one_class.set_function(foo);
one_class.call_function();
one_class.call_ok_function();
one_class.call_nasty_function();
}
As the example suggests, the member function can't be static. Also, I can't redefine the original problem function to receive an object.
Thanks for any help.
Edit
I forgot to mention. I tried changing to std::function, but my original function has more than 10 arguments (It is a Fortran subroutine).
Solution
I made the change to std::function and std::bind as suggested, but did not went for the redesign of a function with more 10 arguments. I decided to create an intermediate function. The following code illustrates what I did, but with fewer variables. Thanks to all.
#include <iostream>
#include <boost/tr1/functional.hpp>
using namespace std;
class TheClass;
typedef tr1::function<void(int *, double *, double *, double *)> ftype;
// Suppose foo is from another file. Can't change the definition
void foo (int n, int m, double *A, double *x, double *b) {
// Performs matrix vector multiplication x = A*b, where
// A is m x n
}
void foo_wrapper (int DIM[], double *A, double *x, double *b) {
foo(DIM[0], DIM[1], A, x, b);
}
class TheClass {
private:
ftype m_function;
void my_function (int DIM[], double *A, double *x, double *b) {
// Change something before performing MV mult.
m_function(DIM, A, x, b);
}
public:
void set_function (ftype p) { m_function = p; }
void call_function() {
int DIM[2] = {2,2};
if (m_function) m_function(DIM, 0, 0, 0);
}
void call_nasty_function() {
TheClass nasty_class;
ftype f = tr1::bind(&TheClass::my_function, this, _1, _2, _3, _4);
nasty_class.set_function(f);
nasty_class.call_function();
}
};
int main () {
TheClass one_class;
one_class.set_function(foo_wrapper);
one_class.call_function();
one_class.call_nasty_function();
}
PS. Creating a std::function with more than 10 variables seemed possible (compiled, but I didn't test) with
#define BOOST_FUNCTION_NUM_ARGS 15
#include <boost/function/detail/maybe_include.hpp>
#undef BOOST_FUNCTION_NUM_ARGS
But creating a std::bind for more than 10 arguments does not seem as easy.
std::function, std::bind, and lambdas are what you are looking for. In short, function pointers are very bad things and should be burned in fire. In long, std::function can store any function object which can be called with the correct signature, and you can use std::bind or a lambda to generate a function object that calls your member function quickly and easily.
Edit: Then you will just have to roll your own std::function equivalent that supports more than 10 arguments.
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 gsl_function. 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?
EDIT
I have tried to use boost::bind like this:
#include <gsl/gsl_integration.h>
#include <boost/bind.hpp>
#include "bondpricecalculator.h"
#include "functions.h"
double integrand (double xi, double t, double x, void * p) {
Functions *functions = (Functions *) p;
double vx = functions->v(x);
return functions->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 = &boost::bind(integrand, xi, t, _1, _2);
F.params = &functions;
double integral_t;
double integral_T;
double error;
int res = gsl_integration_qags(&F, T, 1e+14, 0, 1e-7, 10000, w, &integral_T, &error);
if(res)
{
throw "Error intgrating";
}
int res = gsl_integration_qags(&F, T, 1e+14, 0, 1e-7, 10000, w, &integral_t, &error);
if(res)
{
throw "Error intgrating";
}
return integral_T/integral_t;
}
but I got the following error message:
/home/ga/svn/PhD/inflation/cpp/ioi/bondpricecalculator.cpp:20: error: cannot convert ‘boost::_bi::bind_t<double, double (*)(double, double, double, void*), boost::_bi::list4<boost::_bi::value<double>, boost::_bi::value<double>, boost::arg<1>, boost::arg<2> > >*’ to ‘double (*)(double, void*)’ in assignment
I found below code at.
http://bytes.com/topic/c/answers/657124-interface-problem
// Use in combination with boost::bind.
template<class F>
static double gslFunctionAdapter( double x, void* p)
{
// Here I do recover the "right" pointer, safer to use static_cast
// than reinterpret_cast.
F* function = static_cast<F*>( p );
return (*function)( x );
}
template<class F>
gsl_function convertToGslFunction( const F& f )
{
gsl_function gslFunction;
const void* p = &f;
assert (p != 0);
gslFunction.function = &gslFunctionAdapter<F>;
// Just to eliminate the const.
gslFunction.params = const_cast<void*>( p );
return gslFunction;
}
and use this like
gslFunction gslF = convertToGslFunction( boost::bind( &Sde::drift, &sde, _1 ) );
Take a look at this simple example of combining boost::bind and boost::function.
I'm guessing from all those "gsl_" prefixes that the library is not C++, but plain C. Which means it doesn't grok C++ closures (functors). You can't pass a C++ functor to a C function. You'll have to pass void pointers around, cross your fingers and reinterpret_cast them into C oblivion.
Though bradgonesurfing has given a nice answer that will work for converting closures into gsl_functions without any further thought, I would like to share with you the idiom for doing a direct translation from C++ into C.
Supposing you have the closure:
double a;
[&a](double x){return a+x;}
You would convert translate this into an equivalent function pointer idiom as follows:
struct paramsAPlusX{
double* a;
paramsAPlusX(double & a_):a(&a_){}
}
double funcAPlusX(double x, void* params){
paramsAPlusX* p= (paramsAPlusX*)params;
return *(p->a) + x;
}
//calling code:
double a;
paramsAPlusX params(a);
gsl_function f;
f.function=funcAPlusX;
f.params=¶msAPlusX;
//use f here.
Many C libraries use this sort of idiom, and they don't all use a struct for it (they frequently pass it as two separate parameters to the function) so automatic conversion isn't always possible.
I recently discovered that in C++ you can overload the "function call" operator, in a strange way in which you have to write two pair of parenthesis to do so:
class A {
int n;
public:
void operator ()() const;
};
And then use it this way:
A a;
a();
When is this useful?
This can be used to create "functors", objects that act like functions:
class Multiplier {
public:
Multiplier(int m): multiplier(m) {}
int operator()(int x) { return multiplier * x; }
private:
int multiplier;
};
Multiplier m(5);
cout << m(4) << endl;
The above prints 20. The Wikipedia article linked above gives more substantial examples.
There's little more than a syntactic gain in using operator() until you start using templates. But when using templates you can treat real functions and functors (classes acting as functions) the same way.
class scaled_sine
{
explicit scaled_sine( float _m ) : m(_m) {}
float operator()(float x) const { return sin(m*x); }
float m;
};
template<typename T>
float evaluate_at( float x, const T& fn )
{
return fn(x);
}
evaluate_at( 1.0, cos );
evaluate_at( 1.0, scaled_sine(3.0) );
A algorithm implemented using a template doesn't care whether the thing being called is a function or a functor, it cares about the syntax. Either standard ones (e.g. for_each()) or your own. And functors can have state, and do all kinds of things when they are called. Functions can only have state with a static local variable, or global variables.
If you're making a class that encapsulates a function pointer, this might make the usage more obvious.
The compiler can also inline the functor and the function call. It cannot inline a function pointer, however. This way, using the function call operator can significantly improve performance when it is used for example with the standard C++ libary algorithms.
For example for implementing generators:
// generator
struct Generator {
int c = 0;
virtual int operator()() {
return c++;
}
};
int sum(int n) {
Generator g;
int res = 0;
for( int i = 0; i < n; i++ ) {
res += g();
}
return res;
}
I see potential to yet one exotic use:
Suppose you have object of unknown type and have to declare another variable of same type, like this:
auto c=decltype(a*b)(123);
When such pattern used extensively, decltype become very annoying.
This case can occur when using some smart type system that automatically invent type of result of functions and operators based on types of arguments.
Now, if each specialization of each type of that type system equipped with
magic definition of operator() like this:
template<????> class Num<???>{
//specific implementation here
constexpr auto operator()(auto...p){return Num(p...);}
}
decltype() no more needed, you can write simply:
auto c=(a*b)(123);
Because operator() of object redirects to constructor of its own type.