[英]C++ function pointer to member function
I have a worker class, which takes a callback function pointer initialization in the constructor.我有一个工人 class,它在构造函数中进行回调 function 指针初始化。 I would like to instantiate the worker in my class, and provide a pointer to a member function as a callback.我想在我的 class 中实例化工作人员,并提供指向成员 function 的指针作为回调。
The worker class:工人 class:
class Worker
{
public:
typedef int (*callFunct)(int);
Worker(callFunct callback = nullptr);
~Worker();
private:
callFunct m_callback = nullptr;
};
Worker::Worker(callFunct callback) : m_callback(callback)
{
}
and here is my class, where I would like to have Worker
instance and a member callback function:这是我的 class,我想在其中拥有Worker
实例和成员回调 function:
class myClass
{
public:
myClass();
~myClass() = default;
private:
int myCallback(int x);
Worker m_worker {&myClass::myCallback};
};
Unfortunately this does not compile:不幸的是,这不能编译:
error: could not convert '{&myClass::myCallback}' from '<brace-enclosed initializer list>' to 'Worker'
I am aware that when dealing with pointer to a member class I have to provide the instance object as well.我知道在处理指向成员 class 的指针时,我还必须提供实例 object 。 But what is the correct way to do in this situation, when I need to have pointer to class member?但是在这种情况下,当我需要指向 class 成员的指针时,正确的做法是什么?
Pointers to non-member functions are not the same as pointers to (non-static) member functions!指向非成员函数的指针与指向(非静态)成员函数的指针不同!
The difference is that a (non-static) member function needs an object to be called on, which pointers to non-member function doesn't have.不同之处在于(非静态)成员 function 需要调用 object ,指向非成员 function 的指针没有。
You can use std::function
and lambdas to create the callback:您可以使用std::function
和lambdas来创建回调:
class Worker
{
public:
using callFunct = std::function<int(int)>;
Worker(callFunct callback)
: m_callback(callback)
{
}
private:
callFunct m_callback;
};
class myClass
{
public:
myClass()
: m_worker([this](int x) { return myCallback(x); })
{
}
private:
int myCallback(int x);
Worker m_worker;
};
Or if the callback doesn't need to acces the myClass
object, then make the function static
:或者,如果回调不需要访问myClass
object,则制作 function static
:
class myClass
{
public:
myClass();
private:
static int myCallback(int x);
Worker m_worker {&myClass::myCallback};
};
[As mentioned by others in comments to the question] [正如其他人在对该问题的评论中提到的那样]
Or a plain lambda that does what myClass::myCallback
would do.或者一个普通的 lambda 做myClass::myCallback
会做的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.