溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++11中bind綁定器和function函數(shù)對象實例分析

發(fā)布時間:2022-07-15 09:55:35 來源:億速云 閱讀:137 作者:iii 欄目:開發(fā)技術(shù)

這篇文章主要介紹了C++11中bind綁定器和function函數(shù)對象實例分析的相關(guān)知識,內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇C++11中bind綁定器和function函數(shù)對象實例分析文章都會有所收獲,下面我們一起來看看吧。

一. bind1st和bind2nd

1.C++ STL中的綁定器

  • bind1st:operator()的第一個形參變量綁定成一個確定的值

  • bind2nd:operator()的第二個形參變量綁定成一個確定的值

C++11從Boost庫中引入了bind綁定器和function函數(shù)對象機制

bind可用于給多元函數(shù)降元:Bind + 二元函數(shù)對象 = 一元函數(shù)對象

#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>//泛型算法
#include<ctime>
using namespace std;
template<typename Container>
void showContainer(Container& con)
{
	//typename Container::iterator it=con.begin();
	auto it = con.begin();
	for (; it != con.end(); ++it)
	{
		cout << *it << " ";
	}
	cout << endl;
}
int main()
{
	vector<int> vec;
	srand(time(nullptr));
	for (int i = 0; i < 20; ++i)
	{
		vec.push_back(rand() % 100 + 1);
	}
	showContainer(vec);

	sort(vec.begin(), vec.end());//默認(rèn)從小到大排序
	showContainer(vec);

	//greater需要二元函數(shù)對象
	sort(vec.begin(), vec.end(), greater<int>());//從大到小排序
	showContainer(vec);

	/*
	把70按順序插入到vec容器中 ->找第一個小于70的數(shù)字
	operator()(const T &val)
	greater a>b
	less a<b
	綁定器+二元函數(shù)對象=》一元函數(shù)對象
	bind1st:+greater bool operator()(70,const_Ty&_Right)
	bind2nd:+less bool operator()(const_Ty &_Left,70)
	*/
	auto it1 = find_if(vec.begin(), vec.end(), bind1st(greater<int>(), 70));
	if (it1 != vec.end())
	{
		vec.insert(it1, 70);
	}
	showContainer(vec);
	return 0;
}

2.bind1st和bind2nd的底層原理實現(xiàn)

綁定器本身是一個函數(shù)對象

#include<iostream>
#include<vector>
#include<functional>
#include<algorithm>
#include<ctime>
using namespace std;
template<typename Container>
void showContainer(Container& con)
{
	auto it = con.begin();
	for (; it != con.end(); ++it)
	{
		cout << *it << " ";
	}
	cout << endl;
}
//遍歷兩個迭代器之間的元素,如果滿足函數(shù)對象的運算,就返回當(dāng)前的迭代器,如果都不滿足就返回end
template<typename Iterator,typename Compare>
Iterator my_find_if(Iterator first, Iterator last, Compare comp)
{
	//這里傳入的comp是封裝好的一元函數(shù)對象
	for (; first != last; ++first)
	{
		if (comp(*first))//獲取容器的一個元素
		{
			return first;
		}
	}
	return last;
}
template<typename Compare,typename T>
class _mybind1st//綁定器是函數(shù)對象的一個應(yīng)用
{
public:
	//這里傳入的comp是二元函數(shù)對象
	_mybind1st(Compare comp,T val)
		:_comp(comp),_val(val){}
	//通過重載operator()把二元函數(shù)對象封裝為一元函數(shù)對象
	bool operator()(const T& second)
	{
		return _comp(_val, second);
	}
private:
	Compare _comp;
	T _val;
};
template<typename Compare,typename T>
_mybind1st<Compare, T> mybind1st(Compare comp, const T& val)
{
	//直接使用函數(shù)模板,好處是可以進行類型的推演
	//這里傳入的comp是一個二元函數(shù)對象
	//通過二元函數(shù)對象構(gòu)造一元函數(shù)對象
	//綁定器本身是一個函數(shù)對象,也就是重載了operator()
	return _mybind1st<Compare, T>(comp, val);
}
int main()
{
	vector<int> vec;
	srand(time(nullptr));
	for (int i = 0; i < 20; ++i)
	{
		vec.push_back(rand() % 100 + 1);
	}
	showContainer(vec);

	sort(vec.begin(), vec.end());//默認(rèn)從小到大排序
	showContainer(vec);

	//greater需要二元函數(shù)對象
	sort(vec.begin(), vec.end(), greater<int>());//從大到小排序
	showContainer(vec);

	auto it1 = my_find_if(vec.begin(), vec.end(), mybind1st(greater<int>(), 70));
	if (it1 != vec.end())
	{
		vec.insert(it1, 70);
	}
	showContainer(vec);

	return 0;
}

二. 模板的完全特例化和非完全特例化

有完全特例化優(yōu)先匹配完全特例化,有部分特例化就匹配部分特例化,沒有的話就從原模板自己實例化

#include<iostream>
using namespace std;
template<typename T>
class Vector
{
public:
	Vector() { cout << "call Vector template init" << endl; }
};
//對char*類型提供完全特例化版本
template<>
class Vector<char*>
{
public:
	Vector() { cout << "call Vector<char*> init" << endl; }
};
//對指針類型提供的部分特例化版本(部分:只知道是個指針,但是指針的類型是什么不知道)
template<typename Ty>
class Vector<Ty*>
{
public:
	Vector() { cout << "call Vector<Ty*> init" << endl; }
};
//指針函數(shù)指針(有返回值,有兩個形參變量)提供的部分特例化
template<typename R,typename A1,typename A2>
class Vector<R(*)(A1, A2)>
{
public:
	Vector() { cout << "call Vector<R(*)(A1,A2)> init" << endl; }
};
//針對函數(shù)(有一個返回值,有兩個形參變量)類型提供的部分特例化
template<typename R, typename A1, typename A2>
class Vector<R(A1, A2)>
{
public:
	Vector() { cout << "call Vector<R(A1,A2)> init" << endl; }
};
int sum(int a, int b) { return a + b; }
int main()
{
	Vector<int> vec1;
	Vector<char*> vec2;
	Vector<int*> vec3;
	Vector<int(*)(int, int)> vec4;
	Vector<int(int, int)> vec5;

	//注意區(qū)分函數(shù)類型和函數(shù)指針類型
	typedef int(*PFUNC1)(int, int);
	PFUNC1 pfunc1 = sum;
	cout << pfunc1(10, 20) << endl;

	typedef int PFUNC2(int, int);
	PFUNC2* pfunc2 = sum;
	cout << (*pfunc2)(10, 20) << endl;
	return 0;
}

C++11中bind綁定器和function函數(shù)對象實例分析

#include<iostream>
#include<typeinfo>
using namespace std;
//T包含了所有大的類型
template<typename T>
void func(T a)
{
	cout << typeid(T).name() << endl;
}
int sum(int a, int b) { return a + b; }

//把所有形參類型都取出來
template<typename R, typename A1, typename A2>
void func2(R(*a)(A1, A2))
{
	cout << typeid(R).name() << endl;
	cout << typeid(A1).name() << endl;
	cout << typeid(A2).name() << endl;
}
template<typename R,typename T,typename A1,typename A2>
void func3(R(T::*a)(A1, A2))
{
	cout << typeid(R).name() << endl;
	cout << typeid(T).name() << endl;
	cout << typeid(A1).name() << endl;
	cout << typeid(A2).name() << endl;
}
class Test
{
public:
	int sum(int a, int b) { return a + b; }
};
int main()
{
	//func(10);//int
	//func("aaa");//const char *
	func(sum);
	func2(sum);
	func3(&Test::sum);
	return 0;
}

C++11中bind綁定器和function函數(shù)對象實例分析

三. function函數(shù)對象

綁定器,函數(shù)對象,lambda表達式本質(zhì)上都是函數(shù)對象,只能使用在一條語句中,但是如果想要在多條語句中使用,就需要function

使用function函數(shù)需要注意:

  • 函數(shù)類型實例化function;

  • 通過function調(diào)用operator()函數(shù)的時候,需要根據(jù)函數(shù)類型傳入相應(yīng)的參數(shù)。

#include<iostream>
#include<functional>
using namespace std;
void hello1()
{
	cout << "hello world!" << endl;
}
void hello2(string str)
{
	cout << str << endl;
}
int sum(int a, int b)
{
	return a + b;
}
int main()
{
	//從function的模板定義處,看到希望用一個函數(shù)類型實例化function
	function<void()> func1 = hello1;
	func1();//func1.operator() => hello1()

	function<void(string)> func2 = hello2;
	func2("hello hello2!");

	function<int(int, int)> func3 = sum;
	cout << func3(2, 3) << endl;

	function<int(int, int)> func4 = [](int a, int b)->int {return a + b; };
	cout << func4(3, 4) << endl;
	return 0;
}

C++11中bind綁定器和function函數(shù)對象實例分析

function不僅可以留下普通全局函數(shù)的類型,對于類的成員方法也可以進行類型保留:

#include<iostream>
#include<functional>
using namespace std;

class Test
{
public://必須依賴一個對象void(Test::*pfunc)(string)
	void hello(string str) { cout << str << endl; }
};
int main()
{
	//成員方法一經(jīng)編譯都會多一個當(dāng)前類型的this指針
	function<void (Test*, string)> func = &Test::hello;
	Test t;
	//對于成員方法的調(diào)用需要依賴一個成員對象
	func(&t, "call Test::hello!");
	return 0;
}

function的特點:可以把所有函數(shù)、綁定器、函數(shù)對象和lambda表達式的類型保留起來,在其他地方都可以使用。否則綁定器、lambda表達式就只能使用在語句中。

#include<iostream>
#include<functional>
#include<map>
using namespace std;
void doShowAllBooks(){ cout << "查看所有書籍信息" << endl; }
void doBorrow() { cout << "借書" << endl; }
void doBack() { cout << "還書" << endl; }
void doQueryBooks() { cout << "查詢書籍" << endl; }
void doLoginOut() { cout << "注銷" << endl; }
int main()
{
	int choice = 0;
	//使用function函數(shù)對象完成
	map<int, function<void()>> actionMap;
	actionMap.insert({ 1,doShowAllBooks });
	actionMap.insert({ 2,doBorrow });
	actionMap.insert({ 3,doBack });
	actionMap.insert({ 4,doQueryBooks });
	actionMap.insert({ 5,doLoginOut });
	for (;;)
	{
		cout << "------------------" << endl;
		cout << "1.查看所有書籍信息" << endl;
		cout << "2.借書" << endl;
		cout << "3.還書" << endl;
		cout << "4.查詢書籍" << endl;
		cout << "5.注銷" << endl;
		cout << "------------------" << endl;
		cout << "請選擇:";
		cin >> choice;

		auto it = actionMap.find(choice);
		if (it == actionMap.end())
		{
			cout << "輸入數(shù)字無效,重新選擇" << endl;
		}
		else
		{
			it->second();
		}
		//不好,因為這塊代碼無法閉合,無法做到“開-閉”原則,也就是說這塊代碼隨著需求的更改需要一直改,永遠也閉合不了,避免不了要產(chǎn)生很多問題
		/*
		switch(choice)
		{
			case 1:break;
			case 2:break;
			case 3:break;
			case 4:break;
			case 5:break;
			default:break;
		}
		*/
	}
	return 0;
}

function的實現(xiàn)原理:

#include<iostream>
#include<functional>
using namespace std;

void hello(string str) { cout << str << endl; }
int sum(int a, int b) { return a + b; }

template<typename Fty>
class myfunction{};
/*
template<typename R,typename A1>
class myfunction<R(A1)>
{
public:
	//typedef R(*PFUNC)(A1);
	using PFUNC = R(*)(A1);
	myfunction(PFUNC pfunc):_pfunc(pfunc){}
	R operator()(A1 arg)
	{
		return _pfunc(arg);
	}
private:
	PFUNC _pfunc;
};

template<typename R, typename A1,typename A2>
class myfunction<R(A1,A2)>
{
public:
	//typedef R(*PFUNC)(A1);
	using PFUNC = R(*)(A1,A2);
	myfunction(PFUNC pfunc) :_pfunc(pfunc) {}
	R operator()(A1 arg1,A2 arg2)
	{
		return _pfunc(arg1,arg2);
	}
private:
	PFUNC _pfunc;
};
*/
//...表示可變參,A表示的是一組1類型,個數(shù)任意
template<typename R, typename... A>
class myfunction<R(A...)>
{
public:
	using PFUNC = R(*)(A...);
	myfunction(PFUNC pfunc) :_pfunc(pfunc) {}
	R operator()(A... arg)
	{
		return _pfunc(arg...);
	}
private:
	PFUNC _pfunc;
};
int main()
{
	myfunction<void(string)> func1(hello);
	func1("hello world");
	myfunction<int(int, int)> func2(sum);
	cout << func2(10, 20) << endl;
	return 0;
}

四. bind和function實現(xiàn)線程池

#include<iostream>
#include<functional>
using namespace std;
using namespace placeholders;


//C++11 bind 綁定器=>返回的結(jié)果是一個函數(shù)對象
void hello(string str) { cout << str << endl; }
int sum(int a, int b) { return a + b; }
class Test
{
public:
	int sum(int a, int b) { return a + b; }
};

int main()
{
	//bind是函數(shù)模板,可以自動推演模板類型參數(shù)
	bind(hello, "Hello bind!")();
	cout << bind(sum, 20, 30)() << endl;
	cout << bind(&Test::sum, Test(), 20, 30)() << endl;
	
	//function只接受一個類型,綁定器可以給相應(yīng)的函數(shù)綁定固定的參數(shù),綁定器只能使用在語句當(dāng)中
	//參數(shù)占位符,綁定器出了語句,無法繼續(xù)使用
	bind(hello, _1)("hello bind 2");
	cout << bind(sum, _1, _2)(20, 30) << endl;
	
	//此處把bind返回的綁定器binder就復(fù)用起來了
	function<void(string)> func1 = bind(hello, _1);
	func1("hello china!");
	func1("hello shan xi!");
	func1("hello da li!");

}
#include<iostream>
#include<functional>
#include<thread>
#include<vector>
using namespace std;
using namespace placeholders;

//線程類
class Thread
{
public:
	Thread(function<void(int)> func,int no):_func(func),_no(no){}
	thread start()
	{
		thread t(_func,_no);
		return t;
	}
private:
	function<void(int)> _func;
	int _no;
};
//線程池類
class ThreadPool
{
public:
	ThreadPool(){}
	~ThreadPool()
	{
		//釋放thread對象占用的堆資源
		for (int i = 0; i < _pool.size(); i++)
		{
			delete _pool[i];
		}
	}
	//開啟線程池
	void startPool(int size)
	{
		for (int i = 0; i < size; i++)
		{
			//不管是C++里面的thread還是Linux里面的pthread需要的線程函數(shù)都是一個C函數(shù),是不能夠使用成員方法的,因為它是C的函數(shù)類型,不可能把成員方法的函數(shù)指針給一個C的函數(shù)指針,接收不了。所以就需要綁定,把runInThread所依賴的參數(shù)全部綁定
			_pool.push_back(new Thread(bind(&ThreadPool::runInThread, this, _1),i));
		}
		for (int i = 0; i < size; i++)
		{
			_handler.push_back(_pool[i]->start());
		}
		for (thread& t : _handler)
		{
			t.join();
		}
	}
private:
	vector<Thread*> _pool;
	vector<thread> _handler;
	//把runInThread這個成員方法充當(dāng)線程函數(shù)
	void runInThread(int id)
	{
		cout << "call runInThread! id:" << id << endl;
	}
};
int main()
{
	ThreadPool pool;
	pool.startPool(10);
	return 0;
}

五. lambda表達式

  • 函數(shù)對象的應(yīng)用:使用在泛型算法參數(shù)傳遞、比較性質(zhì)、自定義操作、優(yōu)先級隊列和智能指針

  • 函數(shù)對象的缺點:需要先定義一個函數(shù)對象類型,但是類型定義完后可能只是用在了定義的地方,后面可能不會再用了,沒有必要為了需要一個函數(shù)對象定義一個類型,這個類型就永遠在代碼當(dāng)中。

C++11函數(shù)對象的升級版 => lambda表達式:

  • lambda表達式:底層依賴函數(shù)對象的機制實現(xiàn)的。

  • lambda表達式語法:[捕獲外部變量](形參列表) ->返回值{操作代碼};

如果lambda表達式的返回值不需要,那么“->返回值”可以省略

[捕獲外部變量]

  • [ ]:表示不捕獲任何外部變量

  • [=]:以傳值的方式捕獲外部的所有變量

  • [&]:以傳引用的方式捕獲外部的所有變量[this]:捕獲外部的this指針

  • [=,&a]:以傳值的方式捕獲外部的所有變量,但是a變量以傳引用的方式捕獲

  • [a,b]:以傳值的方式捕獲外部變量a和b

  • [a,&b]:a以值傳遞捕獲,b以傳引用的方式捕獲

1.lambda表達式的實現(xiàn)原理

#include<iostream>
using namespace std;
template<typename T=void>
class TestLambda01
{
public:
	void operator()()
	{
		cout << "hello world" << endl;
	}
};
template<typename T = int>
class TestLambda02
{
public:
	TestLambda02() {}
	int operator()(int a, int b)
	{
		return a + b;
	}
};
template<typename T = int>
class TestLambda03
{
public:
	TestLambda03(int a,int b):ma(a),mb(b){}
	void operator()()const
	{
		int tmp = ma;
		ma = mb;
		mb = tmp;
	}
private:
	mutable int ma;
	mutable int mb;
};
class TestLambda04
{
public:
	TestLambda04(int &a,int &b):ma(a),mb(b){}
	void operator()()const
	{
		int tmp = ma;
		ma = mb;
		mb = tmp;
	}
private:
	int& ma;
	int& mb;
};
int main()
{
	auto func1 = []()->void {cout << "hello world" << endl; };
	func1();

	auto func2 = [](int a, int b)->int {return a + b; };
	cout << func2(20, 30) << endl;

	int a = 10;
	int b = 20;
	//按值傳遞a,b值未被改變
	auto func3 = [a, b]()mutable
	{
		int tmp = a;
		a = b;
		b = tmp;
	};
	func3();
	cout << "a:" << a << " b:" << b << endl;
	
	//傳引用值a,b值被改變
	auto func4 = [&]()
	{
		int tmp = a;
		a = b;
		b = tmp;
	};
	func4();
	cout << "a:" << a << " b:" << b << endl;

	cout << "--------------------" << endl;
	TestLambda01<> t1;
	t1();
	TestLambda02<> t2;
	cout << t2(20, 30) << endl;
	TestLambda03<> t3(a,b);
	t3();
	cout << "a:" << a << " b:" << b << endl;
	TestLambda04 t4(a,b);
	t4();
	cout << "a:" << a << " b:" << b << endl;
	
	return 0;
}

C++11中bind綁定器和function函數(shù)對象實例分析

mutable:成員變量本身也不是常量,只不過在常方法中this指針被修飾成const,在聲明成員變量前加mutable,可以在const方法中修改普通的成員變量

lambda表達式后面修飾mutable相當(dāng)于在它的所有成員變量添加一個mutable修飾。

2.lambda表達式的應(yīng)用實踐

lambda表達式應(yīng)用于泛型算法:

#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

int main()
{
	vector<int> vec;
	for (int i = 0; i < 20; ++i)
	{
		vec.push_back(rand() % 100 + 1);
	}
	sort(vec.begin(), vec.end(),
		[](int a, int b)->bool
		{
			return a > b;
		});
	for (int val : vec)
	{
		cout << val << " ";
	}
	cout << endl;
	//65按序插入序列 要找一個小于65的數(shù)字
	auto it = find_if(vec.begin(), vec.end(),
		[](int a)->bool {return a < 65; });
	if (it != vec.end())
	{
		vec.insert(it, 65);
	}
	for (int val : vec)
	{
		cout << val << " ";
	}
	cout << endl;
	for_each(vec.begin(), vec.end(), [](int a)
	{
		if (a % 2 == 0)
			cout << a << " ";
	});
	cout << endl;
	return 0;
}

既然lambda表達式只能使用在語句中,如果想跨語句使用之前定義好的lambda表達式,采用function類型來表示函數(shù)對象的類型。

哈希表的應(yīng)用:

#include<iostream>
#include<vector>
#include<map>
#include<functional>
using namespace std;
int main()
{
	//auto只能出現(xiàn)在根據(jù)右邊表達式推導(dǎo)左邊的類型,只能使用在函數(shù)的局部作用域的范圍之內(nèi)
	//預(yù)先lambda表達式不知道需要先存儲lambda表達式類型
	map<int, function<int(int, int)>> caculateMap;
	caculateMap[1] = [](int a, int b)->int {return a + b; };
	caculateMap[2] = [](int a, int b)->int {return a - b; };
	caculateMap[3] = [](int a, int b)->int {return a * b; };
	caculateMap[4] = [](int a, int b)->int {return a / b; };

	cout << "請選擇";
	int choice;
	cin >> choice;
	cout << caculateMap[choice](10, 15) << endl;
	return 0;
}

智能指針自定義刪除器:

#include<iostream>
#include<vector>
#include<functional>
using namespace std;
int main()
{
	unique_ptr<FILE, function<void(FILE*)>>
		ptr1(fopen("data.txt", "w"), [](FILE* pf) {fclose(pf); });
}

傳入函數(shù)對象使得容器元素按照指定方式排列:

#include<iostream>
#include<vector>
#include<functional>
#include <queue>
using namespace std;

class Data
{
public:
	Data(int val1=10,int val2=10):ma(val1),mb(val2){}
	int ma;
	int mb;
};
int main()
{
	//優(yōu)先級隊列
	//priority_queue<Data> queue;
	using FUNC = function<bool(Data&, Data&)>;
	priority_queue<Data, vector<Data>, FUNC>
		maxHeap([](Data& d1, Data& d2)->bool
			{
				return d1.mb > d2.mb;
			});
	maxHeap.push(Data(10, 20));
	maxHeap.push(Data(15, 15));
	maxHeap.push(Data(20, 10));
}

關(guān)于“C++11中bind綁定器和function函數(shù)對象實例分析”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“C++11中bind綁定器和function函數(shù)對象實例分析”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI