Integrate a public but non static member function with ALGLIB - c++

I am trying to integrate a member function of a class, and needs some help! I cannot declare the function static because this function uses non-static private members (more specifically use a private member which is another class). I am using C++17 and cannot downgrade
I write below a Minimum (Non) Working Example that mimic my problem. The aim is to find what to put instead of the four question marks '????' in alglib::autogkintegrate(s, ????, params).
The alglib::autogkintegrate function takes three arguments:
a 'state' which contains the current value of the integration, integral boundaries, other stuff?)
The function f to integrate which must be of the prototype void f(double x, double xminusa, double bminusx, double &y, void *ptr)
an optional pointer void *ptr which contains extra parameters for the function f
Here is the non working example:
#include <functional>
#include <iostream>
#include <cmath>
#include "integration.h"
class Foo;
class Bar;
/*****************************
Class Foo
*****************************/
class Foo
{
public:
// Constructor
Foo(Bar *b, int toto);
// Function to integrate
void f(double x, double xminusa, double bminusx, double &y, void *ptr);
private:
Bar *m_bar;
int m_toto;
};
Foo::Foo(Bar *b, int toto) : m_bar(b), m_toto(toto)
{}
void Foo::f(double x, double xminusa, double bminusx, double &y, void *ptr)
{
double *param = (double *) ptr;
double p1 = param[0];
double p2 = param[1];
y = exp(this->m_toto*x)/(p1 * p2);
}
/*****************************
Class Bar
*****************************/
class Bar
{
friend Foo;
public:
// Constructor
Bar();
private:
int m_a, m_b;
};
Bar::Bar() : m_a(2), m_b(5)
{}
/*****************************
Main program
*****************************/
int main(int argc, char *argv[])
{
Bar* b = new Bar();
Foo f(b, 87);
double arrayParams[2] = {1, 2};
double (*params)[2] = &arrayParams;
alglib::autogkstate s;
double v;
alglib::autogkreport rep;
alglib::autogksmooth(0, 1, s);
alglib::autogkintegrate(s, ????, params);
alglib::autogkresults(s, v, rep);
return 0;
}
If I declare the function f as static (and remove this->m_totoin f), then I can integrate fby using alglib::autogkintegrate(s, Foo::f, params);. So the problem is really to get access to the function f.
I tried to define a pointer to member function (which explains #include <functional>) but failed to use it in alglib::autogkintegrate(s, ????, params);
To repeat my question: I want to integrate a member function of a class using ``Alglib``` in C++
Useful links:
https://www.alglib.net/translator/man/manual.cpp.html#gs_using section 8.5
https://www.alglib.net/translator/man/manual.cpp.html#example_autogk_d1
P.S.: I also posted this question at http://forum.alglib.net/viewtopic.php?f=2&t=4352 which is a dedicated forum to Alglib (but looks much less active than Stack Overflow, hence my double post. If I get an answer there, I will copy-paste here, and vice-versa)

I found a solution on http://www.newty.de/fpt/callback.html using a global variable (sorry...). I post here the code adapted to my question if anyone needs it:
#include <functional>
#include <iostream>
#include <cmath>
#include "integration.h"
class Foo;
class Bar;
void* pt2Object; // global variable which points to an arbitrary object
/*****************************
Class Foo
*****************************/
class Foo
{
public:
// Constructor
Foo(Bar *b, int toto);
// Function to integrate
void f(double x, double xminusa, double bminusx, double &y, void *ptr);
// Wrapper
static void Wrapper_To_Call_f(double x, double xminusa, double bminusx, double &y, void *ptr);
private:
Bar *m_bar;
int m_toto;
};
Foo::Foo(Bar *b, int toto) : m_bar(b), m_toto(toto)
{}
void Foo::f(double x, double xminusa, double bminusx, double &y, void *ptr)
{
double *param = (double *) ptr;
double p1 = param[0];
double p2 = param[1];
y = exp(this->m_toto*x)/(p1 * p2);
// y = exp(x)/(p1 * p2);
}
void Foo::Wrapper_To_Call_f(double x, double xminusa, double bminusx, double &y, void *ptr)
{
// explicitly cast global variable <pt2Object> to a pointer to TClassB
// warning: <pt2Object> MUST point to an appropriate object!
Foo* mySelf = (Foo*) pt2Object;
// call member
mySelf->f(x, xminusa, bminusx, y, ptr);
}
/*****************************
Class Bar
*****************************/
class Bar
{
friend Foo;
public:
// Constructor
Bar();
private:
int m_a, m_b;
};
Bar::Bar() : m_a(2), m_b(5)
{}
/*****************************
Main program
*****************************/
int main(int argc, char *argv[])
{
Bar* b = new Bar();
// Create Foo
Foo myFoo(b, 1);
// Assign global variable which is used in the static wrapper function
// important: never forget to do this!!
pt2Object = (void*) &myFoo;
double arrayParams[2] = {1, 2};
double (*params)[2] = &arrayParams;
alglib::autogkstate s;
double v;
alglib::autogkreport rep;
alglib::autogksmooth(0, 1, s);
alglib::autogkintegrate(s, Foo::Wrapper_To_Call_f, params);
alglib::autogkresults(s, v, rep);
std::cout << v << std::endl;
return 0;
}

Related

Calling class constructor inside another class using a pointer to a member function

I am trying to initialize an object of a class inside a member function of another class. The problem is that I need to pass a function pointer to the constructor. I do not know how I can make this. This is the error:
no matching function for call to ‘inheritance01::inheritance01(double (inheritance02::*&)(double))’
inheritance01 LT (func);
The code below shows the problem.
class Base01 {
public:
Base01(double (*)(double));
virtual double calc(double) = 0;
double (*ptr_fd() const)(double) { return ptr_fd_; }
private:
double (*ptr_fd_)(double);
};
Base01::Base01(double (*f)(double))
: ptr_fd_(f)
{
}
//----------------------------------------------------
class inheritance01 : public Base01 {
public:
inheritance01(double (*ptr_f)(double));
virtual double calc(double);
};
inheritance01::inheritance01(double (*pf)(double))
: Base01(pf)
{
}
double inheritance01::calc(double t) { return 2.0 * t; }
//###################################################
class Base02 {
public:
Base02(double);
virtual double solution(double, double) = 0;
double a() { return a_; };
private:
const double a_;
};
Base02::Base02(double aa)
: a_(aa)
{
}
//------------------------------------------------------
class inheritance02 : public Base02 {
public:
inheritance02(double, double);
virtual double solution(double, double);
//static double sol_aux (double);
private:
double sol_aux(double);
const double b;
//double (inheritance02::*fptrsol_aux)(double u) = &inheritance02::sol_aux;
typedef double (inheritance02::*fptr)(double u);
fptr func;
};
inheritance02::inheritance02(double aa, double bb)
: Base02(aa)
, b(bb)
{
//func = double (*sol_aux)(double);
//func = &inheritance02::sol_aux;
}
//--------------------------------------------------
double inheritance02::sol_aux(double u)
{
return (a() + b) / u;
}
//--------------------------------------------------
double inheritance02::solution(double x, double t)
{
//inheritance01 LT (&func);
//inheritance01 LT (this->func);
//inheritance01 LT (&fptrsol_aux);
inheritance01 LT(func); // Here is the problem
return LT.calc(x + t);
}
//########################################################
#include <iostream>
int main()
{
inheritance02 obj(1.0, 1.0);
double value = obj.solution(1.0, 1.0);
std::cout << "value = " << value << std::endl;
return 0;
}
As the comment by #Eljay says, you are creating a typedef for a pointer to member function here:
typedef double (inheritance02::*fptr)(double u);
However, the constructor of inheritance01 takes a regular function pointer as an argument:
inheritance01( double (*ptr_f)(double));
so this line:
inheritance01 LT(func); // Here is the problem
doesn't work because the types don't match up (pointer to member functions are not convertible to function pointers).
The easy fix would be to make func a regular function pointer, like this:
typedef double (*fptr)(double u);
and everything should work fine.
Here's a demo.
Although I am not able to declare the 'func_' parameter as const and private (I do not know how to return a std::function) the following code solves my problem:
#include <iostream>
#include <functional>
using namespace std;
class Base01
{
public:
Base01( std::function<double (double)> );
virtual double calc( double ) = 0;
//function<double (double)> func { return func_; }
function<double (double)> func;
private:
//const function<double (double)> func_;
};
Base01::Base01( function<double (double)> f) : func(f) {}
//----------------------------------------------------
class inheritance01:public Base01
{
public:
inheritance01( function<double (double)> );
virtual double calc( double );
};
inheritance01::inheritance01 (function<double (double)> f): Base01(f){}
double inheritance01::calc(double t) { return Base01::func(2.0*t); }
//###################################################
class Base02
{
public:
Base02(double);
virtual double solution(double, double) = 0;
double a(){return a_;};
private:
const double a_;
};
Base02::Base02(double aa): a_(aa) {}
//------------------------------------------------------
class inheritance02 : public Base02
{
public:
inheritance02( double, double );
virtual double solution(double, double);
private:
double sol_aux (double);
const double b;
};
inheritance02::inheritance02 (double aa, double bb)
: Base02(aa), b(bb)
{}
//--------------------------------------------------
double inheritance02::sol_aux(double u) { return (a()+b)/u; }
//--------------------------------------------------
double inheritance02::solution(double x, double y)
{
inheritance01 LT ( bind( &inheritance02::sol_aux, this, placeholders::_1) );
return LT.calc(x+y);
}
//########################################################
int main()
{
inheritance02 obj (1.0,1.0);
double value = obj.solution(1.0,1.0);
std::cout << "value = " << value << std::endl;
return 0;
}

Passing function to class in C++

I want to store a function in a class and simply call this function inside a member function. I know that this is possible using function pointers but I want to use std::function for this.
Here is some code that is not working but should demonstrate what I want to do:
double foo(double a, double b){
return a + b;
}
class Test{
private:
std::function<double(double,double)> foo_ ;
public:
Test(foo);
void setFoo(foo) {foo_ = foo;}
double callFoo(double a, double b){return foo_(a,b);}
};
int main(int argc, char const *argv[]) {
Test bar = Test(foo);
bar.callFoo(2,3);
return 0;
}
You almost did it right, but forgot the types in your constructor and setFoo:
#include <functional>
#include <iostream>
double foo(double a, double b) {
return a + b;
}
class Test {
private:
std::function<double(double, double)> foo_;
public:
// note the argument type is std::function<>
Test(const std::function<double(double, double)> & foo) : foo_(foo) {}
// note the argument type is std::function<>
void setFoo(const std::function<double(double, double)>& foo) { foo_ = foo; }
double callFoo(double a, double b) { return foo_(a, b); }
};
int main(int argc, char const *argv[]) {
Test bar = Test(foo);
bar.callFoo(2, 3);
return 0;
}
By the way, it is often beneficial to use a typedef to avoid long and complicated names, for example if you do
typedef std::function<double(double,double)> myFunctionType
you can use myFunctionType everywhere, which is easier to read (provided you invent a better name than "myFunctionType") and more tidy.

passing a functor to a constructor in C++

Would that be possible to help me to pass a functor, such as :
struct BFunc
{
double operator()(const double x, const double y, const double z){
return 0.1;
}
};
to a the constructor of a class:
class foo
{
int n;
public:
foo();
foo(int nn, &bfunc):n(nn),f(func()){
}
double getResult(double x){
return f(x);
}
}
Thanks,
Thank you all for your quick response. I solved it, by declaring a variable of type functor as bellow. But I was wondering if it is possible to do it without that. The point is I wanted to create a class, which I pass a function as boundary condition and a range to it, so it creates a 2D or 3D matrix of coordinates which gives zero to all points inside and zero to all points outside. I wanted to make it as general as possible. Eventually I ended up to follow following method.
using namespace std;
struct functor {
int a=11;
int operator () (int x) const {
cout << a << endl;
return 2*x;
}
};
class myclass {
int y=0;
functor af;// ** I did not wanted to have this line and make it generic ** //
public:
template <typename F> myclass(const F & f):af(f){
//af=f;//auto af(f);
y=f(5);
cout<<"y is"<<y<<endl;
int z=af(5);
cout<<"z is"<<z<<endl;
cout<<" why "<<typeid(af).name()<<endl;
}
int getFuncX(int x){
int y=af(x);
return y;
}
};
int main(int argc, char **argv) {
functor f = {5};
myclass c(f);
cout<<" See What happens: "<<c.getFuncX(71)<<endl;
return 0;
}
Sorry if it is messy! As you guessed I am a beginner.
Thanks

Pointer to a member-function

I would like to do the following:
I have two classes, A and B, and want to bind a function from A to a function from B so that whenever something calls the function in B, the function from A is called.
So basically, this is the scenario:
(important A and B should be independent classes)
This would be class A:
class A {
private:
// some needed variables for "doStuff"
public:
void doStuff(int param1, float *param2);
}
This is class B
class B {
private:
void callTheFunction();
public:
void setTheFunction();
}
And this is how I would like to work with these classes:
B *b = new B();
A *a = new A();
b->setTheFunction(a->doStuff); // obviously not working :(
I've read that this could be achieved with std::function, how would this work? Also, does this have an impact in the performance whenever callTheFunction() is called? In my example, its a audio-callback function which should call the sample-generating function of another class.
Solution based on usage C++11 std::function and std::bind.
#include <functional>
#include <stdlib.h>
#include <iostream>
using functionType = std::function <void (int, float *)>;
class A
{
public:
void doStuff (int param1, float * param2)
{
std::cout << param1 << " " << (param2 ? * param2 : 0.0f) << std::endl;
};
};
class B
{
public:
void callTheFunction ()
{
function (i, f);
};
void setTheFunction (const functionType specificFunction)
{
function = specificFunction;
};
functionType function {};
int i {0};
float * f {nullptr};
};
int main (int argc, char * argv [])
{
using std::placeholders::_1;
using std::placeholders::_2;
A a;
B b;
b.setTheFunction (std::bind (& A::doStuff, & a, _1, _2) );
b.callTheFunction ();
b.i = 42;
b.f = new float {7.0f};
b.callTheFunction ();
delete b.f;
return EXIT_SUCCESS;
}
Compile:
$ g++ func.cpp -std=c++11 -o func
Output:
$ ./func
0 0
42 7
Here's a basic skeleton:
struct B
{
A * a_instance;
void (A::*a_method)(int, float *);
B() : a_instance(nullptr), a_method(nullptr) {}
void callTheFunction(int a, float * b)
{
if (a_instance && a_method)
{
(a_instance->*a_method)(a, b);
}
}
};
Usage:
A a;
B b;
b.a_instance = &a;
b.a_method = &A::doStuff;
b.callTheFunction(10, nullptr);
This i basic a solution
class A {
private:
// some needed variables for "doStuff"
public:
void doStuff(int param1, float *param2)
{
}
};
typedef void (A::*TMethodPtr)(int param1, float *param2);
class B {
private:
TMethodPtr m_pMethod;
A* m_Obj;
void callTheFunction()
{
float f;
(m_Obj->*m_pMethod)(10, &f);
}
public:
void setTheFunction(A* Obj, TMethodPtr pMethod)
{
m_pMethod = pMethod;
m_Obj = Obj;
}
};
void main()
{
B *b = new B();
A *a = new A();
b->setTheFunction(a, A::doStuff); // now work :)
}

Member-Function Pointers With Default Arguments

I am trying to create a pointer to a member function which has default arguments. When I call through this function pointer, I do not want to specify an argument for the defaulted argument. This is disallowed according to the standard, but I have never before found anything that the standard disallowed that I could not do in some other conformant way. So far, I have not found a way to do this.
Here is code illustrating the problem I'm trying to solve:
class MyObj
{
public:
int foo(const char* val) { return 1; }
int bar(int val = 42) { return 2; }
};
int main()
{
MyObj o;
typedef int(MyObj::*fooptr)(const char*);
fooptr fp = &MyObj::foo;
int r1 = (o.*fp)("Hello, foo.");
typedef int(MyObj::*barptr)(int);
barptr bp1 = &MyObj::bar;
int r2 = (o.*bp1)(); // <-- ERROR: too few arguments for call
typedef int (MyObj::*barptr2)();
barptr2 bp2 = &MyObj::bar; // <-- ERROR: Can't convert from int(MyObj::*)(int) to int(MyObj::*)(void)
int r3 = (o.*bp2)();
return 0;
}
Any ideas on how to do this in conformant C++ if I do not want to specify any values for the defaulted arguments?
EDIT: To clarify the restrictions a bit. I do not want to specify any default arguments either in the call or in any typedef. For example, I do not want to do this:
typedef int(MyObj::*barptr)(int = 5);
...nor do I want to do this:
typedef int(MyObj::*barptr)(int);
...
(o.barptr)(5);
It would be rather strange to expect the function pointers to work the way you expect them to work in your example. "Default argument" is a purely compile-time concept, it is a form of syntactic sugar. Despite the fact that default arguments are specified in the function declaration or definition, they really have nothing to do with the function itself. In reality default arguments are substituted at the point of the call, i.e. they are handled in the context of the caller. From the function's point of view there's no difference between an explicit argument supplied by the user or a default one implicitly supplied by the compiler.
Function pointers, on the other hand, are run-time entities. They are initialized at run time. At run-time default arguments simply don't exist. There's no such concept as "run-time default arguments" in C++.
Some compilers will allow you to specify default arguments in function pointer declaration, as in
void foo(int);
int main() {
void (*pfoo)(int = 42) = foo;
pfoo(); // same as 'pfoo(42)'
}
but this is not standard C++ and this does not appear to be what you are looking for, since you want the "default argument " value to change at run time depending on the function the pointer is pointing to.
As long as you want to stick with genuine function pointers (as opposed to function objects, aka functors) the immediate workaround would be for you to provide a parameter-less version of your function under a different name, as in
class MyObj
{
public:
...
int bar(int val = 42) { return 2; }
int bar_default() { return bar(); }
};
int main()
{
MyObj o;
typedef int (MyObj::*barptr2)();
barptr2 bp2 = &MyObj::bar_default;
int r3 = (o.*bp2)();
return 0;
}
This is, of course, far from elegant.
One can actually argue that what I did above with bar_default could have been implicitly done by the compiler, as a language feature. E.g. given the class definition
class MyObj
{
public:
...
int bar(int val = 42) { return 2; }
...
};
one might expect the compiler to allow the following
int main()
{
MyObj o;
typedef int (MyObj::*barptr2)();
barptr2 bp2 = &MyObj::bar;
int r3 = (o.*bp2)();
return 0;
}
where the pointer initialization would actually force the compiler to implicitly generate an "adapter" function for MyObj::bar (same as bar_default in my previous example), and set bp2 to point to that adaptor instead. However, there's no such feature in C++ language at this time. And to introduce something like that would require more effort than it might seem at the first sight.
Also note that in the last two examples the pointer type is int (MyObj::*)(), which is different from int (MyObj::*)(int). This is actually a question to you (since you tried both in your example): how would you want it to work? With an int (MyObj::*)() pointer? Or with a int (MyObj::*)(int) pointer?
You could create functors instead of function pointers of course.
struct MyFunctor {
int operator() {
return myobj.bar();
}
MyFunctor(MyObj &obj) : myobj(obj) {}
MyObj &myobj;
};
then:
MyFunctor myfunc(o);
myFunctor();
This is not possible given the constraints. Your options are:
Using function wrappers.
Using Functors.
Check out Boost for some handy tools to simplify this.
Task: Suppose you have the following:
class Thing {
public:
void foo (int, double = 3.14) const {std::cout << "Thing::foo(int, double = 3.14) called.\n";}
void goo (int, double = 1.5) const {std::cout << "Thing::goo(int, double = 1.5) called.\n";}
};
void function1 (const Thing& thing, int a, int b, double c) {
// Code A
thing.foo(a,c);
// Code B
thing.foo(b);
// Code C
}
void function2 (const Thing& thing, int a, int b, double c) {
// Code A
thing.goo(a,c);
// Code B
thing.goo(b);
// Code C
}
We want to write a helper function to capture function1 and function2 so that the repeated codes A, B, C need not be written twice.
The following will not compile:
class Thing {
public:
void foo (int, double = 3.14) const {std::cout << "Thing::foo(int, double = 3.14) called.\n";}
void goo (int, double = 1.5) const {std::cout << "Thing::goo(int, double = 1.5) called.\n";}
};
void functionHelper (const Thing& thing, int a, int b, double c, void (Thing::*f)(int, double) const) {
// Code A
(thing.*f)(a,c);
// Code B
// (thing.*f)(b); // Won't compile. Too few arguments passed to (thing.*f), which expects (int, double).
// Code C
}
void function1 (const Thing& thing, int a, int b, double c) {
functionHelper (thing, a, b, c, &Thing::foo);
}
void function2 (const Thing& thing, int a, int b, double c) {
functionHelper (thing, a, b, c, &Thing::goo);
}
First solution (overload of Thing::foo and Thing::goo):
#include <iostream>
class Thing {
public:
void foo (int, double = 3.14) const {std::cout << "Thing::foo(int, double = 3.14) called.\n";}
void foo_default (int a) const {
std::cout << "Thing::foo_default(int) called.\n";
foo(a);
}
void goo (int, double = 1.5) const {std::cout << "Thing::goo(int, double = 1.5) called.\n";}
void goo_default (int a) const {
std::cout << "Thing::goo_default(int) called.\n";
goo(a);
}
};
void functionHelper (const Thing& thing, int a, int b, double c,
void (Thing::*f)(int, double) const, void (Thing::*g)(int) const) {
// Code A
(thing.*f)(a,c);
// Code B
(thing.*g)(b); // This will compile now, since (thing.*g) expects int only as argument.
// Code C
}
void function1 (const Thing& thing, int a, int b, double c) {
functionHelper (thing, a, b, c, &Thing::foo, &Thing::foo_default);
}
void function2 (const Thing& thing, int a, int b, double c) {
functionHelper (thing, a, b, c, &Thing::goo, &Thing::goo_default);
}
int main() {
Thing thing;
function1 (thing, 2, 5, 1.8);
std::cout << '\n';
function2 (thing, 2, 5, 1.8);
}
Output:
Thing::foo(int, double = 3.14) called.
Thing::foo_default(int) called.
Thing::foo(int, double = 3.14) called.
Thing::goo(int, double = 1.5) called.
Thing::goo_default(int) called.
Thing::goo(int, double = 1.5) called.
Second solution (Wrap Thing::foo and Thing::goo into function objects):
#include <iostream>
#include <memory>
class Thing {
public:
void foo (int, double = 3.14) const {std::cout << "Thing::foo(int, double = 3.14) called.\n";}
void goo (int, double = 1.5) const {std::cout << "Thing::goo(int, double = 1.5) called.\n";}
class FooOrGoo {
public:
void operator()(const Thing& thing, int a) const {helper1 (thing, a);}
void operator()(const Thing& thing, int a, double b) {helper2 (thing, a, b);}
virtual ~FooOrGoo() {std::cout << "Thing::FooOrGoo object destroyed.\n";}
private:
virtual void helper1 (const Thing& thing, int a) const = 0;
virtual void helper2 (const Thing& thing, int a, double b) const = 0;
};
class Foo : public FooOrGoo {
virtual void helper1 (const Thing& thing, int a) const override {thing.foo(a);}
virtual void helper2 (const Thing& thing, int a, double b) const override {thing.foo(a, b);}
};
class Goo : public FooOrGoo {
virtual void helper1 (const Thing& thing, int a) const override {thing.goo(a);}
virtual void helper2 (const Thing& thing, int a, double b) const override {thing.goo(a, b);}
};
};
void functionHelper (const Thing& thing, int a, int b, double c, std::unique_ptr<Thing::FooOrGoo> f) {
// Code A
(*f)(thing, a,c);
// Code B
(*f)(thing, b);
// Code C
}
void function1 (const Thing& thing, int a, int b, double c) {
functionHelper (thing, a, b, c, std::unique_ptr<Thing::Foo>(new Thing::Foo)); // 'std::make_unique<Thing::Foo>());' is not supported by GCC 4.8.1.
}
void function2 (const Thing& thing, int a, int b, double c) {
functionHelper (thing, a, b, c, std::unique_ptr<Thing::Goo>(new Thing::Goo)); // 'std::make_unique<Thing::Goo>());' is not supported by GCC 4.8.1.
}
int main() {
Thing thing;
function1 (thing, 2, 5, 1.8);
std::cout << '\n';
function2 (thing, 2, 5, 1.8);
}
Output:
Thing::foo(int, double = 3.14) called.
Thing::foo(int, double = 3.14) called.
Thing::FooOrGoo object destroyed.
Thing::goo(int, double = 1.5) called.
Thing::goo(int, double = 1.5) called.
Thing::FooOrGoo object destroyed.
Which solution do you think is better? I think the second one is more elegant, but there are more lines of code (I couldn't do it without polymorphism).