c++ - 如何使用 std::function 或 Boost 在 C++ 中实现类成员指针?

标签 c++ oop c++11 boost boost-signals2

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

我写了一个示例代码,它使用“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);

关于c++ - 如何使用 std::function 或 Boost 在 C++ 中实现类成员指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27267019/

相关文章:

c++ - 如何使用 std::rel_ops 自动提供比较运算符?

c++ - 从 std::vector 创建/填充 std::set 的 STL 方式

c++ - 为什么 QAction 没有默认构造函数?

c++ - 从使用 numpy.save(...) 保存的文件中将 numpy 数组加载到 C 中

php - CodeIgniter 在同一 Controller 中加载多个模型

c++ - 将 unique_ptr 返回到多态类型

c++ - 链接 SFML 时出错。 LNK2001

c++ - 什么是 istream_view,什么时候使用?

java - 我不明白 'this' 与父类(super class)一起使用

返回指向抽象类的指针的 C++ 函数