std::bind函数模板与占位符关系

//bind函数模板实例化【返回的】函数对象=>bind函数对象
//bind函数模板内部使用的函数对象plus<>()=>封装函数对象
//bind函数模板嵌套一个bind函数对象=>嵌套bind函数对象
//bind函数模板本身

#include<iostream>
#include<functional>
using namespace std;
using namespace std::placeholders;
int main()
{
	auto func=bind(plus<>(), 10, 20);
	int n=func(4);//可以有多个参数但是无值匹配,并发挥效用

	auto func1=bind(multiplies<int>(),bind(plus<int>(),_1,10),2);//嵌套bind中表达式的核定次序是从内向外的
	int n1 = func1(7);//占位符标识需要传入匹配的,10表示内部之间绑定的

	auto func2 = bind(multiplies<int>(), bind(multiplies<int>(), _1, _1), _1);
	int n2 = func2(7);//无论是内层bind还是外层bind 占位符都是与同一个最终参数表【最终外层调用参数表】关联

	auto func3 = bind(divides<int>(), _2,_1);//调用参数表-占位符-传参关系:最终调用参数表参数从左至右第N个参数与站位符 _N匹配【即按数字匹配bind返回的函数对象的调用参数表内的参数次序】【与占位符在bind函数本身内的参数次序无关】【注意一个是返回的函数对象的调用参数表,一个是模板函数bind的实例化参数表】
	int n3 = func3(7,49);//但是bind内封装的函数对象的调用传参次序与【与占位符在bind函数本身内的参数次序同序】
 //	n3 = func3(49);//error:最终调用的参数表参数必须要满足被站位符匹配
	n3 = func3(7,49,2);//true : 返回的函数对象是一个可变参函数对象,可以传递多个参数,多余的参数不使用

	auto func4 = bind(divides<int>(), _3, _1);
//	n3 = func4(49);//error:最终调用的参数表参数必须要满足被站位符匹配【最终调用参数表的参数个数>= _MAX 占位符】【外匹配规则】
	n3 = func4(7,6, 49); //最终调用的参数表参数必须要满足被站位符匹配【最终调用参数表的参数个数>= _MAX 占位符】【外匹配规则】

//	auto func5 = bind(divides<int>(), _3, _1,_2);
//	n3 = func5(7, 6, 49);//error:占位符个数与获取后的类型 要与封装函数对象divides<int>()的调用参数表匹配【内匹配规则】
	return 0;
}
#include<iostream>
#include<functional>
#include<vector>
#include<new>
using namespace std;
using namespace placeholders;
int foo(int a, int b, int c, int d, int e)
{
	int res = a + 2 * b + 3 * c + 4 * d + 5 * e;
	return res;
}
template<typename T,int n>
void fdfasd(T a)
{
	cout << n << endl;
}



template<bool b>
constexpr int kkk;
template<>
 int kkk<true> = 20;
template<>
constexpr int kkk<false> = 30;
int main()
{
	int resflase = kkk<false>;
	int restrue = kkk<true>;

	char szdfalse[kkk<false>];
	//char szdtrue[kkk<true>];

	fdfasd<int,4>(3);
	auto sp = unique_ptr<int[]>(new int[3]{9,8,7});
	int *pa=sp.release();
	delete[]pa;
	auto ps = new auto(3);
	auto g = bind(foo, 1, 2, _2, 4, _1);//占位符按序号之间的相对顺序绑定到foo调用
	int res = g(3, 5);//g的参数按位置绑定到占位符
	

	int z = 3;
	auto pf = [z]()mutable {
		int a = 3;
		z++;
		
		if (a > 0)
			return 0;
		return -1;
	};
	cout << pf() << endl;
	return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值