Hello everyone :) I have a problem with function pointers
My arguments to the callback function:
1) this function: int (* fx) (int, int)
2) variable int: int a 3) another int: int b
Well, the problem that the function that I want to pass to the "callback" is a non-stationary member of the function :( and there are many problems
If someone smarter than me has time to spend, he can see my code :)
#include <iostream>
using namespace std;
class A{
private:
int x;
public:
A(int elem){
x = elem;
}
static int add(int a, int b){
return a + b;
}
int sub(int a, int b){
return x - (a + b);
}
};
void callback( int(*fx)(int, int), int a, int b)
{
cout << "Value of the callback: " << fx(a, b) << endl;
}
int main()
{
A obj(5);
callback(A::add, 10, 20);
int(A::*function1)(int, int) = &A::sub;
cout << "Non static member: " << (obj.*function1)(1, 1) << endl;
int(A::*function2)(int, int) = &A::sub;
int(*function3)(int, int) = obj.*function2;
callback(function3, 1, 1);
}
Is there a way to create my pointer in the way I tried to write, for example int (* fx) (int, int) = something?
I searched a lot, but no one could give me an answer (well, there was an answer: "NO", but I still think I can do something)
, ?
PS:
EDIT1:
- :
template <class T>
void callback2( T* obj, int(T::*fx)(int, int), int a, int b)
{
cout << "Value of the callback: " << (obj->*fx)(a, b) << endl;
}
void callback2( void* nullpointer, int(*fx)(int, int), int a, int b)
{
cout << "Value of the callback: " << fx(a, b) << endl;
}
:
callback2(NULL, &mul, 5, 3); // generic function, it like: int mul(int a, int b){return a*b;}
callback2(NULL, &A::add, 5, 3); //static member function
callback2(&obj, &A::sub, 1, 1); //non static member function
, "callback2" ()...
, () , : callback2?
void callback2(int(*fx)(int, int), int a, int b)<br>
:
callback2(&obj.sub, 1, 3);