将成员函数指针分配为来自另一个函数的回调 [英] Assign a member function pointer as a callback from another function

查看:83
本文介绍了将成员函数指针分配为来自另一个函数的回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类A,该类具有用于回调的函数指针。默认值是类A的一些函数指针,但我想分配类B的一个函数指针。我尝试了 std :: function std: :bind ,但不起作用。我尝试使用此答案,但没有

I have a class A that has a function pointer for a callback. The default values are some function pointer from class A but I want to assign a function pointer from class B. I tried std::function and std::bind but it is not working. I tried to use this answer but without success.

代码为:

#include <iostream>
#include <string>
#include <functional>

class A{
public:
    typedef void(*action)() ;

    A( std::function<void()> a  = nullptr)
    {
        if(a)
            m_Func = a; 
        else
            m_Func = std::bind( (this->*(this->dummyFunction))() );
    }
    std::function<void(void)> m_Func;
    void dummyFunction(void){std::cout<<"dummy function\n" <<std::endl;}
};

class B{
public:
    std::function<void()> m_Bfunc(){ std::cout << "class B func\n" <<std::endl;}
};

int main()
{
  B b;
  A a(b.m_Bfunc);
  a.m_Func();
}

我希望函数 m_Bfunc 运行。

推荐答案

似乎要:

class A{
public:
    A(std::function<void()> a = nullptr)
    {
        if(a)
            m_Func = a; 
        else
            m_Func = [this](){ dummyFunction(); };
    }
    std::function<void()> m_Func;
    void dummyFunction(){std::cout<<"dummy function\n" <<std::endl;}
};

class B{
public:
    void func(){ std::cout << "class B func\n" <<std::endl;}
};

int main()
{
  B b;
  A a([&](){b.func(); });
  a.m_Func();
}

演示

这篇关于将成员函数指针分配为来自另一个函数的回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆