std::bind学习记录

版权声明:本文为CSDN博主「法号大威天龙」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/sinat_34319731/article/details/74386885
本文源于转载,受益匪浅,防止今后找不到故搬运至此,尊重原创

bind 用来绑定一个函数,包括全局函数, 普通成员函数, 静态成员函数, operator函数, 虚函数

但是不包括重载函数,原因是,通过函数名并不知道 因为无法确定需要哪个重载函数实例(vs2013),

#include<iostream>
#include<functional>
using namespace std;
 
int add1(int i, int j, int k)
{
	return i + j + k;
}
 
typedef std::function<void() > fp;
class A
{
public:
 
	A(string& say) :say_(say){}
 
	void foo(string para)
	{
		cout <<"A::foo():"<< "say_:\t"<< say_.c_str() <<"\tpara:\t"<<para.c_str() << endl;
	}
 
	/*void foo(int a, string para)
	{
		cout << "say_:\t" << say_.c_str() << "    para:\t" << para.c_str()<<"   a:"<<a << endl;
	}*/
	virtual void f()
	{
		cout << "A::f()" << endl;
	}
	static const string getId()
	{
		cout << "static const string getId():";
		return num_sta;
	}
 
	int operator()(int i, int j) const 
	{
		return i + j;
	}
 
	void init()
	{
		//std::bind可以表现出多态的行为
		fp f_ = std::bind(&A::f, this);
		f_();
	}
private:
	string say_;
	static string num_sta;
};
 
class B :public A
{
public:
	B(string a):A(a){}
	virtual void f()
	{
		cout << "B::f()" << endl;
	}
};
 
string A::num_sta = "static number";

int main()
{
	//绑定全局函数
	{
		// 函数add2 = 绑定add1函数,参数1不变,参数2不变,参数3固定为10
		auto add2 = std::bind(add1, std::placeholders::_1, std::placeholders::_2, 10);
		std::cout << typeid(add2).name() << endl;
		std::cout << "add2(1,2):\t" << add2(1, 2) << endl;
		std::cout << "___________________________" << endl;
		//函数add2 = 绑定add1函数, 三个参数都不变
		auto add3 = std::bind(add1, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
		int i = 0;
		while (i < 3)
			std::cout << "add2(1,2," << i << ")\t" << add3(1, 2, i++) << "\n" << endl;
		std::cout << "___________________________" << endl;
	}
 
	//绑定成员函数
	{
		string say("string say()");
		A a(say);
		//普通成员函数,(成员函数名,所属类对象,需要绑定的参数和指定的参数)
		//不能绑定重载函数,因为无法确定需要哪个重载函数实例
		auto bind_foo = std::bind(&A::foo /*要绑定对象*/, a /*所属对象(调用者)*/, std::placeholders::_1);
		bind_foo(say);
		//静态成员函数(静态成员函数名,没有所属类对象!!
		auto bind_static = std::bind(&A::getId);
		cout << "bind_static():\t" << bind_static().c_str() << endl;
		std::cout << "___________________________" << endl;
		//operator函数(和绑定成员函数一样)
		auto bind_operator = std::bind(&A::operator(), a, std::placeholders::_1, std::placeholders::_2);
		cout << "bind_operator(5, 10):\t" << bind_operator(5, 10) << endl;
		std::cout << "___________________________" << endl;
 
	}
	//绑定虚函数
	{
		A* pa = new B("new B");
		pa->init();
	}
	return 0;
}

Result:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值