如何使用 std::function 或 boost 在C++中实现类成员指针

How to implement a class member pointer in C++ using std::function or Boost?

本文关键字:实现 C++ 成员 指针 boost std 何使用 function      更新时间:2023-10-16

我想在C++中实现一个面向对象的函数指针(相当于C#中的委托)。

我写了一个示例代码,它使用"MagicFunctionPainter"作为最终类的占位符:

class A
{
public: 
    MagicFunctionPointer p;
    void fireEvent()
    {
         p();
    }
};
class B
{
public:
    void init(A* a)
    {
        a->p = &onEvent;
    }
    void onEvent()
    {
        // in a real-world app, it'd modify class variables, call other functions, ...
    }
};

std::function 或 Boost::Signals2 是否支持?还有其他图书馆支持这种情况吗?

提前谢谢你!

p的类型应为:

std::function<void(void)> // a function taking no arguments, returning nothing

B::init创建此类型的对象:

std::bind(&B::onEvent, this);

你需要绑定它:

 boost::bind(&ClassX::member_function, boost::ref(instance))