关键字-Function使用总结

1.为什么要使用function
C++语言有几种函数调用对象:函数,函数指针,lambda表达式,bind创建的对象
 以及重载了函数调用运算符的类。
对于几个可调用的对象共享同一种调用形式的情况,有时我们会希望把他们看成具有
 相同类型。但问题不同的可调用对象之间并不无法直接赋值。
//普通函数
int add(int i, int j){ return i + j;}

//lambda表达式,其产生一个为命名的函数对象类
auto mod = [](int i, int j) { return i % j;};

//函数对象类
struct divide{
  int operator()(int i, int j) {return i/j; }
};

//当我们定义一个函数类型指针时
typedef int (*OperPtr)(int, int);
OperPtr addPtr = add; 	 //正确
OperPtr modPtr = mod; 	 //正确
OperPtr divPtr = divide(); //错误, divide重载的运算符带有一个隐形的this形参

//为了解决上述问题便引入function模板;
function<OperPtr> f1 = add;
function<OperPtr> f2 = mod;
function<OperPtr> f3 = divide();
2.function的操作(头文件functional)
//构造函数
function<T> f;
function<T> f(nullptr);
function<T> f(obj);
f;			//将f作为条件,但f含有可调用对象时为真。
f(args)		//调用对象
  
//成员
result_type:       		//返回类型
argument_type:     		//定义T有一个实参或两个实参类型
first_argument_type:
second_argument_type:
3.function实际举例
  下例通过map定义一个函数调用运算表,实现简单的二则运算:
①头文件
#ifndef _CALC_H_
#define _CALC_H_

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


class Calc{
	friend istream &operator>>(istream &is, Calc &calc);
	friend ostream &operator<<(ostream &os, Calc &calc);
	
public:
	Calc():first(0), second(0),oper("") {}
private:
	static map<string, function<int (int, int)>> binops;
	int 		first;
	int 		second;
	string oper;	
};


istream &operator>>(istream &is, Calc &calc);
ostream &operator<<(ostream &os, Calc &calc);
 
#endif
②calc源文件
#include "Calc.h"
using namespace std;


map<string, function<int (int, int)>> Calc::binops = {
	{"+", std::plus<int>()},
	{"-", std::minus<int>()}, 
	{"*", std::multiplies<int>()},
	{"/", std::divides<int>()},
	{"%", std::modulus<int>()}};

//输入运算 
istream &operator>>(istream &is, Calc &calc)
{
	is >> calc.first >> calc.oper >> calc.second;
	if(!is)
		calc = Calc();
	return is;
}

//输出运算 
ostream &operator<<(ostream &os, Calc &calc)
{
	auto& binops = Calc::binops; 
	if(binops.end() != binops.find(calc.oper))
	{
		int result = calc.binops[calc.oper](calc.first, calc.second);
		os << calc.first << calc.oper << calc.second << "="	<< result;
	}
	else
	{
		os << "calc can't support this operation!";
	}
	return os;
}
③测试文件
int main(int argc, char** argv) {
	//初始化计算数值
	Calc calc;
	while(cin>>calc)
		cout<<calc<<endl;
	return 0;
} 





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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值