1

我想在 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 支持吗?还有其他支持这种情况的库吗?

先感谢您!

4

2 回答 2

2

的类型p应该是:

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

使用以下命令创建此类型的对象B::init

std::bind(&B::onEvent, this);
于 2014-12-03T08:46:33.213 回答
0

你需要绑定它:

 boost::bind(&ClassX::member_function, boost::ref(instance))
于 2014-12-03T08:41:17.760 回答