C++ 11 | 包装器

function包装器

前面的的文章中我们讲述了C++11中的部分语法,在本篇文章中我们将继续讲解一个新的内容包装器。function包装器也叫做适配器。C++中的function本质是一个类模板 – 对可调用对象类型进行再封装适配。举例来说,现在又一个加法的方法分别有函数、仿函数、类、lambda表达式等不同的方式来进行表达,为了能够有统一的类型可以管理这些同样的方法的对象,就产生了包装器。下面我们就从代码中看一下包装器的使用。

// 我们有这些可调用对象
// 函数指针
int f(int a, int b) {
	cout << "int f(int a, int b)" << endl;
	return a + b;
}
// 仿函数
struct Functor {
public:
	int operator() (int a, int b) {
		cout << "int operator() (int a, int b)" << endl;
		return a + b;
	}
};
// lambda表达式
[](int x, int y){ return x + y; };
int main() {
	// 上述的三种可调用对象都可以使用包装器进行封装变成一种统一的类型来进行调用,但是调用的时候还是调用的各自的对象
	function<int(int, int)> f1 = f;
	function<int(int, int)> f2 = Functor();
	function<int(int, int)> f3 = [](int x, int y) {	return x + y; };
	cout << f1(1, 2) << endl;
	cout << f2(10, 20) << endl;
	cout << f3(1, 3) << endl;
	// 这样我们就可以使用map来进行映射,不同的指令就可以调用不同的方法来执行
	map<string, function<int(int, int)>> opFuncMap;
	opFuncMap["函数指针"] = f;
	opFuncMap["仿函数"] = Functor();
	opFuncMap["lambda"] = [](int a, int b) {
		cout << "[](int a, int b) {return a + b;}" << endl;
		return a + b;
	};
	cout << opFuncMap["lambda"](1, 2) << endl;
}

包装器的类模板原型

std::function在头文件 < functional >
// 类模板原型如下
template < class T > function; // undefined
template < class Ret, class… Args >
class function< Ret(Args…) >;
模板参数说明:
Ret: 被调用函数的返回类型
Args…:被调用函数的形参

下面我们可以来看一道题目来更加深入的理解包装器的使用

150. 逆波兰表达式求值

class Solution {
public:
    int evalRPN(vector<string>& tokens) {
        stack<int> s;
        map<string, function<int(int, int)>> oFuncMap = {
            {"+", [](int x, int y){return x + y;}},
            {"-", [](int x, int y){return x - y;}},
            {"*", [](int x, int y){return x * y;}},
            {"/", [](int x, int y){return x / y;}}
        };
        for (auto str : tokens) {
            if (oFuncMap.count(str)) {
                int right = s.top();
                s.pop();
                int left = s.top();
                s.pop();
                s.push(oFuncMap[str](left, right));
            }
            else {
                s.push(stoi(str));
            }
        }
        return s.top();
    }
};

在上述的代码中我们就结合了map、lambda和包装器来进行处理,让不同的字符表示不同的函数执行方法。

类中的成员函数与静态成员函数的包装

对于类中成员函数函数与静态成员函数我们想要使用包装器,就需要有一些的不同:

class Plus {
public:
	Plus(int rate = 2)
		:_rate(rate)
	{}
	static int plusi(int a, int b) {
		return a + b;
	}
	double plusd(double a, double b) {
		return a + b * _rate;
	}
private:
	int _rate = 2;
};
int main()
{
	// 对于上述的函数,我们想要使用包装器就要按照如下的方式使用:
	// function<int(int, int)> f1 = Plus::plusi;//普通函数与静态成员函数函数名就是指针, 非静态需要添加& -- 规定,静态成员函数可以添加也可以不添加
	function<int(int, int)> f1 = &Plus::plusi; 
	function<double(Plus, double, double)> f2 = &Plus::plusd; // 这里添加的是Plus, 使用对象调用
	function<double(Plus*, double, double)> f3 = &Plus::plusd; // 这里添加的是Plus*
	
	cout << f1(1, 2) << endl;
	cout << f2(Plus(), 20, 20) << endl; // 使用对象进行传递可以使用匿名对象
	cout << f2(Plus(3), 30, 20) << endl;
	
	Plus pl1(3);
	cout << f2(pl1, 20, 20) << endl;
	
	Plus pl2(3);
	cout << f3(&pl2, 20, 20) << endl; // 指针不能使用匿名对象,因为不能取地址
}

bind

std::bind函数定义在头文件中,是一个函数模板,它就像一个函数包装器(适配器),接受一个可调用对象(callable object),生成一个新的可调用对象来“适应”原对象的参数列表。一般而言,我们用它可以把一个原本接收N个参数的函数fn,通过绑定一些参数,返回一个接收M个(M可以大于N)参数的新函数。同时,使用std::bind函数还可以实现参数顺序调整等操作。

函数原型

// 原型如下:
template <class Fn, class… Args>
/* unspecified */ bind (Fn&& fn, Args&&… args);
// with return type (2)
template <class Ret, class Fn, class… Args>
/*unspecified */ bind (Fn&& fn, Args&&… args);
可以将bind函数看作是一个通用的函数适配器,它接受一个可调用对象,生成一个新的可调用对象来“适应”原对象的参数列表。
调用bind的一般形式:auto newCallable = bind(callable,arg_list);
其中,newCallable本身是一个可调用对象,arg_list是一个逗号分隔的参数列表,对应给定的callable的参数。当我们调用newCallable时,newCallable会调用callable,并传给它arg_list中的参数。
arg_list中的参数可能包含形如_n的名字,其中n是一个整数,这些参数是“占位符”,表示
newCallable的参数,它们占据了传递给newCallable的参数的“位置”。数值n表示生成的可调用对象中参数的位置:_1为newCallable的第一个参数,_2为第二个参数,以此类推.

调整参数的顺序

void Print(int a, int b) {
	cout << a << " " << b << endl;
	cout << "void Print(int a, int b)" << endl;
}

int main() {
	Print(1, 2);
	function<void(int, int)> RPrint = bind(Print, placeholders::_2, placeholders::_1);
	//auto RPrint = bind(Print, placeholders::_2, placeholders::_1);
	RPrint(10, 20);
}
// 按照上述的输出就可以看出,虽然使用bind进行了绑定,但是使用的还是Print

调整参数的个数

class Sub {
public:
	Sub(int rate)
		:_rate(rate)
	{}
	int func(int a, int b) { // 在内核中有三个参数this指针,,无法使用上述的function进行统一的管理,因此使用绑定可以定死一个参数,这样就变为了两个参数的function,可以进行传递
		return (a - b) * _rate;
	} 
private:
	int _rate;
};

class Solution {
public:
	int evalRPN(vector<string>& tokens) {
		stack<int> st;
		map<string, function<int(int, int)>> opFuncMap =
		{
			{ "+", [](int i, int j) {return i + j; } },
			{ "-", bind(&Sub::func, Sub(3), placeholders::_1, placeholders::_2) },
		};
		// ...
	}
};

int main()
{
	function<int(Sub, int, int)> fSub = &Sub::func;
	// 绑定可以将某个参数绑死
	function<int(int, int)> func = bind(&Sub::func, Sub(3), _1, _2);
	function<int(Sub, int)> func1 = bind(&Sub::func, _1, 10, _2);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值