大家好:)我有一个关于函数指针的问题
我的“回调”函数参数是:
1)像这样的函数:int(*fx)(int,int)
2)一个int变量:int a
3)另一个int:int b
好吧,问题是我想传递给“回调”的函数是一个非静态函数成员:(并且有很多问题
如果比我聪明的人有时间的话,他可以看看我的代码:)
#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);
//PASSING A POINTER TO A STATIC MEMBER FUNCTION -- WORKS!!
// output = 'Value of the callback: 30'
callback(A::add, 10, 20);
//USING A POINTER TO A NON-STATIC MEMBER FUNCTION -- WORKS!!
int(A::*function1)(int, int) = &A::sub;
// output = 'Non static member: 3'
cout << "Non static member: " << (obj.*function1)(1, 1) << endl;
//PASSING A POINTER TO A NON-STATIC MEMBER FUNCTION -- aargh
// fallita! tutto quello sotto non funziona --> usa i funtori???
// puoi creare una classe wrapper ma non riuscirai mai a chiamare da callback
int(A::*function2)(int, int) = &A::sub;
int(*function3)(int, int) = obj.*function2; //[error] invalid use of non-static member function
callback(function3, 1, 1);
}
有一种方法可以按照我尝试编写的方式创建指针,例如 int(*fx)(int, int) = some?
我搜索了很多,但没有人能给我答案(嗯,有一个答案:“不”,但我仍然认为我可以做点什么)
我还听说了函子,在这种情况下它们可以帮助我吗?
感谢任何人
PS:抱歉我的英语不好
编辑1:
我可以使用这样的东西:
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's 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”传递给第一个参数(对象)......
对于那些不理解我的(糟糕的)解释的人来说,问题是:我可以删除回调2函数中的第一个参数吗?
原型将是
void callback2(int(*fx)(int, int), int a, int b)<br>
我会这样称呼:
callback2(&obj.sub, 1, 3);