function函数对象类应用实例

介绍

function对象可接受:绑定器、函数对象、lambda表达式

使用案例1

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

void hello1()
{
	cout << "hellowro" << endl;
}

void hello2(string str)
{
	cout << str << endl;
}

int sum(int a, int b)
{
	return a + b;
}

class Test
{
public:
	// 必须依赖一个对象 void (Test::*pfunc)(string str)
	void hello(string str)
	{
		cout << str << endl;
	}
};

int main()
{

	function<void()> func1 = hello1;
	func1(); // <=> func1.operator()() 即 hello1()

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

	function<int(int, int)> func3 = sum;
	cout << func3(20, 20) << endl;
	
	
	// lambda
	function<int(int, int)> func4 = [](int a, int b)->int{ return a + b; };
	cout << func4(200, 20) << endl;

	// 注意类型
	function<void(Test*, string)> func5 = &Test::hello;
	Test t1;
	func5(&t1, "call Test::hello"); 
	//func5(&Test(), "call Test::hello!"); // error,新版本&必须跟左值
	return 0;
}

使用案例2:建立函数表

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

void doShowAllBooks() { cout << "查看所有书籍信息" << endl; }
void doBorrow() { cout << "借书" << endl; }
void doReturn() { cout << "还书" << endl; }
void doQueryBooks() { cout << "查询书籍" << endl; }
void doLogOut() { cout << "注销" << endl; }

int main()
{
	int choice = 0;
	// 很好的满足了开闭原则
	map<int, function<void()>> actionMap;
	actionMap.insert({ 1, doShowAllBooks });
	actionMap.insert({ 2, doBorrow });
	actionMap.insert({ 3, doReturn });
	actionMap.insert({ 4, doQueryBooks });
	actionMap.insert({ 5, doLogOut });

	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);
		map<int, function<void()>>::iterator it = actionMap.find(choice);
		if (it == actionMap.end())
		{
			cout << "输入数字无效,重新选择!" << endl;
		}
		else
		{
			it->second();
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值