使object_pool支持3个以上构造函数参数

本文介绍如何使用Boost库中的object_pool并扩展其构造函数支持更多参数的方法。通过模板辅助函数实现了一个四参数构造函数的例子,并讨论了如何避免过多参数的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

boost中的object_pool的construct函数最多支持3个参数,但是可以扩展,我用了辅助函数模板的方式:

#include <boost/pool/object_pool.hpp>
using namespace boost;

class demo_class
{
public:
	int x,y,z,w;
	demo_class(int x=1,int y=2,int z=3,int w=4):x(x),y(y),z(z),w(w) {}
	void show() {cout<<x<<" "<<y<<" "<<z<<" "<<w<<endl;}
};

template <typename P,typename T0,typename T1,typename T2,typename T3>
inline typename P::element_type* construct(P& p,const T0 & a0, const T1 & a1, const T2 & a2,const T3& a3)
{
	typename P::element_type* mem=p.malloc();
	assert(mem!=NULL);
	new (mem)P::element_type(a0,a1,a2,a3);
	return mem;
}

int _tmain(int argc, _TCHAR* argv[])
{
	object_pool<demo_class> opl;
	demo_class* p=construct<object_pool<demo_class>,int,int,int,int>(opl,1,2,3,4);
	p->show();
	return 0;
}


不过看起来也挺别扭的,希望不要写带太多参数的构造函数,如果实在多,数据之间又关联,可以定义成结构体,避免增加参数个数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值