std::bind是如何实现绑定成员函数的

非成员函数

非成员函数可以用指针直接调用

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

using namespace std;

void NonMemFunc()
{
	std::cout << __func__ << "()" << std::endl;
}

int main()
{
	void (*f)() = NonMemFunc;
    f();
	return 0;
}

// 输出:NonMemFunc()

成员函数

成员函数(静态函数除外)是无法直接用指针调用,函数调用必须有对应的对象通过class_obj.*func()class_obj->*func()

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

using namespace std;

class test
{
public:
    test() {}

    void print(const std::string &str)
    {
        std::cout << __func__ << "() " << str << std::endl;
    }

    ~test() {}
};

int main(int argc, char **argv)
{
    test t;

    auto func = &test::print;
    (t.*func)("ffff");
    return 0;
}

// 输出:print() ffff

由此可以看出,两种函数的调用方式不同,故std::bind在实现时是会对是否为成员函数作区分的。而标准库正好提供了这一个函数std::is_member_function_pointer<decltype(NonMemFunc)>::value,value为true则表示函数为成员函数,为false表示为非成员函数。
如下图是bind函数的实现
_Bind_helper有个数据类型为type,其就是一个执行接口,由其内部在进行区分。
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
圈出来的这三种分别是非成员函数,有参成员函数,有参成员函数
在这里插入图片描述
具体的实现可以参考 https://zhuanlan.zhihu.com/p/143764465

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值