是否可以将函数(指针?)保存到对象中?

vim*_*loc 5 c++ function-pointers

我已经搜索了这个,但我想我只是让自己更加困惑.

我想要做的是在一个对象中保存一个函数指针,并在稍后的另一个线程中调用它.

我想象的是一个构造函数,它将获取一个函数指针和将传递给该函数指针的参数.该对象还将具有run()方法,该方法将运行所述函数指针和wait_until_completed()方法,该方法将阻塞直到该函数已运行.

如果有意义的话,函数指针应该是来自另一个对象的函数.例如

Foo::*Bar(int);
Run Code Online (Sandbox Code Playgroud)

我有使用pthread_cond_t的wait_until_completed()工作,但我坚持这个函数指针的事情,感觉我只是在圈子里跑来跑去.

有什么建议?

编辑:这是为学校(任何我的一般理解)所以第三方图书馆不能工作:/

我觉得我做了一个非常糟糕的工作来解释这个,让我给出一些示例代码(不包括所有同步的东西)

class Foo
{
public:
    Foo(void (Bar::*function) (int), int function_param)
    {
        // Save the function pointer into this object
        this->function = &function;

        // Save the paramater to be passed to the function pointer in this object
        param = function_param;
    }

    run()
    {
        (*function)(param);
    }

private:
    // The function pointer
    void (Bar::*function) (int) = NULL;

    // The paramater to pass the function pointer
    int param;
}
Run Code Online (Sandbox Code Playgroud)

这简直就是我要做的事情.但是,我不确定它是语法还是我是愚蠢的,但我无法弄清楚如何实际执行此操作并将其编译.

几点思考?并感谢到目前为止的所有建议:)

Xeo*_*Xeo 9

首先,您需要使用typedef您的函数类型,以便更轻松地重用它并减少错误的可能性.

typedef void (Bar::*function_type)(int);
Run Code Online (Sandbox Code Playgroud)

现在你可以像这样使用typedef:

Foo(function_type func, int func_param)
    : function_(func)
    , param_(func_param)
{
}
Run Code Online (Sandbox Code Playgroud)

此外,使用初始化列表初始化成员变量是个好主意(您可以在此处找到有关初始化列表的更多信息).
但是,您仍然无法调用该函数.类成员函数,也称为绑定函数必须与实例化对象一起使用,因为它们绑定到它们.你的run函数必须看起来像这样(你也忘了返回类型):

void run(Bar* object){
  (object->*function_(param_));
}
Run Code Online (Sandbox Code Playgroud)

它使用特殊->*运算符通过成员函数指针调用成员函数.
此外,您无法直接在类中初始化大多数变量(只有静态积分常量,如a static const int i = 5;).现在,您将能够实例化一个Foo对象并在其上调用run函数.
这里有一个完全可编译的例子:

#include <iostream>
using namespace std;

class Bar{
public:
    void MyBarFunction(int i){
        cout << i << endl;
    }
};

class Foo
{
public:
    typedef void (Bar::*function_type)(int);

    Foo(Bar* object, function_type function, int function_param)
        : object_(object)  // save the object on which to call the function later on
        , function_(function)  // save the function pointer
        , param_(function_param)  // save the parameter passed at the function
    {
    }


    void Run()
    {
        (object_->*function_)(param_);
    }

private:
    // The object to call the function on
    Bar* object_;

    // The function pointer
    function_type function_;

    // The paramater to pass the function pointer
    int param_;
};

int main(void){
    // create a Bar object
    Bar bar;
    // create a Foo object, passing the Bar object
    // and the Bar::myBarFunction as a parameter
    Foo foo(&bar, &Bar::MyBarFunction, 5);

    // call Bar::MyBarFunction on the previously passed Bar object 'bar'
    foo.Run();

    cin.get();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这可能有点消化,但我希望这有助于您理解成员函数指针以及如何使用它们.:)