如何将函数对象传递给期望void *指针的函数?

How can I pass a function object to a function that expects a void * pointer

本文关键字:函数 void 指针 期望 对象      更新时间:2023-10-16

我有一个函数,它期望被传递给一个函数的普通引用

void func(* pOtherFunc);

我想创建多个函数与轻微的变化和传递那些-我正在考虑的函数对象。我如何将这个函数传递给函数对象?

传统函数指针:

我认为你指向函数的指针没有很好地定义。下面是一个示例:

void test (int a)   // first function to be called 
{   cout <<"TEST function: "<<a;  }
void test2 (int a)   // other function to be called
{   cout <<"second test function: "<<a; }
void func( void (*pOtherFunc)(int a) )  // your function 
{
    cout << "Call:  "; 
    (*pOtherFunc)(10);
    cout<<endl; 
}
int main(int ac, char**av) 
{
    func (test); 
    func (test2); 
        return 0;
}

如果你想有一个指向你的函数的变量,你可以这样写:

void (*pf)(int a); 
pf = test; 
func(pf); 

如你所见,你的函数指针应该总是有相同的签名;否则,编译器将不知道如何向它们传递参数。

函数对象的替代

另一种选择是使用对象,特别是在函数带有附加参数的情况下。为此,您将需要一个基对象,并且所有其他"函数对象"都应该从基对象派生。

class myFunction {
public:
    virtual void myfunc(int a) {  cout <<"class function: "<<a<<endl; }
};
class mynewFunction : myFunction {
public: 
    virtual void myfunc(int a) {  cout <<"other class function: "<<a<<endl; }
};   

然后可以使用这些类来实例化对象或指向对象的指针:

int main(int ac, char**av) 
{
    myFunction f; 
    mynewFunction g; 
    f.myfunc(10); 
    g.myfunc(10); 
}

当然,您可以将这些对象作为参数传递给其他函数。

代码:

void func(* pOtherFunc );

你不能传递一个函数对象。你可以给它传递一个指向函数的指针。

void func(int(*pf)(int)) { cout << pf(3); }
int f(int x) { return x; }
int g(int x) { return x*x; }
int main() {
    cout << "Hello World" << endl; 
    int (*p1)(int) = (int(*)(int))f;
    int (*p2)(int) = (int(*)(int))g;
    func(p1);
    func(p2);
    return 0;
}

传递函数对象需要一个不同的签名