波奇学C++:function包装器和智能指针(一)

function包装器

相当于适配器,用于对可调用对象(函数指针,仿函数,lambda)进行封装,使得他们的类型统一。

double func(double d)
{
	return d / 4;
}
struct func1
{
	double operator()(double d)
	{
		return d / 4;
	}
};
int main()
{
    function<double(double)> f1 = [](double d) {return d / 4; };
    function<double(double)> f2 = func;
    function<double(double)> f3 = func1();
    return 0;
}

function<return-type(parameter-type)> = lambda/函数指针/仿函数匿名对象

包装后的对象可以放在容器中,并调用。

vector<function<double(double)>> v = { f1,f2,f3 };
for (auto e : v)
{
	cout << e(4) << endl;
}

functional 的 bind绑定

bind绑定

从传参的角度对封装好的可调用对象进一步限制

改变参数对应位置

int Sub(int a, int b)
{
	return a - b;
}


function<int(int, int)> rSub = bind(Sub, placeholders::_1,placeholders::_2);
cout << rSub(10, 5) << endl; // 5
function<int(int, int)> rrSub = bind(Sub, placeholders::_2, placeholders::_1);
cout << rrSub(10, 5) << endl; // -5

rSub的10 对应_1,_1对应a

rrS 的 10 对应_1,  _1 对应b

减少传参

int Add(int a, int b,int rate)
{
	return (a - b)*rate;
}
function<int(int, int)> radd = bind(Add, placeholders::_1, placeholders::_2,10);
cout << radd(10, 5) << endl; //(10-5)*10

 Add经过封装后参数只剩下a,b,rate的值被限定成10

function<int(int, int)> radd = bind(Add, placeholders::_1, 10,placeholders::_2);
cout << radd(10, 5) << endl; // 0

由此可见,bind里面的_1,_2 和函数是以相对位置映射的,而调用时radd的参数顺序和_1数字编号有关和位置顺序无关。

bind绑定类域中的函数

class A
{
public:
	static int add(int a, int b)
	{
		return a + b;
	}
	int aadd(int a, int b)
	{
		return a + b;
	}
};

function<int(int,int)> rfunc1 = bind(&A::add, placeholders::_1, placeholders::_2); 
// 静态成员函数
A a; 
function<int(int, int)> rfunc2 = bind(&A::aadd,&a, placeholders::_1, placeholders::_2);
function<int(int, int)> rfunc3 = bind(&A::aadd, A(), placeholders::_1, placeholders::_2);
// 成员函数实际三个参数,this,因此我们可以传对象指针或者匿名对象

bind的第一个参数实际上是函数地址,底层上bind绑定是仿函数。

智能指针

利用类对象的构造和析构函数来控制指针的生成和释放,即RAII

template<class T>
class SmartPtr
{
public:
	SmartPtr(T* ptr)
		:_ptr(ptr)
	{}
	~SmartPtr()
	{
		cout << "delete pointer"<<_ptr << endl;
	}
private:
	T* _ptr;
};
void test()
{
	SmartPtr<string> ptr(new string());
}

当test函数结束时,会调用析构函数释放指针。

智能指针的重载符号

class SmartPtr
{
public:
	SmartPtr(T* ptr)
		:_ptr(ptr)
	{}
	T& operator*()
	{
		return *_ptr;
	}
	T* operator->()
	{
		return _ptr;
	}
	~SmartPtr()
	{
		cout << "delete pointer"<<_ptr << endl;
	}
private:
	T* _ptr;
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值