boost之实用工具

1.noncopyable用于禁止复制和拷贝的类继承。声明拷贝和赋值函数为私有,将运行时的错误转化为编译期的错误。

#include <iostream>
#include <boost/pool/singleton_pool.hpp>
using namespace std;
using namespace boost;

class Mynoncopy 
{
public:
	Mynoncopy(){}
private:
	Mynoncopy(const Mynoncopy&);
	void operator=(const Mynoncopy&);
};
class Test:Mynoncopy
{

};
int main()
{
	Test t1;
	//Test t2 = t1;//禁止拷贝
	Test t3;
	//t3 = t1;//禁止复制
	return 0;
	
}

 2.assgin,有时候我们测试需要大量的数据,需要重复调用insert,或者push_back(),assgin主要解决这类问题

 

#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <boost/assign.hpp>
using namespace std;
using namespace boost::assign;


int main()
{
	vector<int> v;
	v+= 1,2,3,4,5,6;
	set<string> s;
	s+="cpp","java","c#";
	map<int,string> m;
	m+= make_pair(1,"one"),make_pair(2,"two");
	return 0;
	
}

 还有一种调用方式是使用()操作符但是需要辅助函数:

#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <boost/assign.hpp>
using namespace std;
using namespace boost::assign;


int main()
{
	vector<int> v;
	v+= 1,2,3,4,5,6;
	push_back(v)(1)(2)(3)(4);
	set<string> s;
	s+="cpp","java","c#";
	map<int,string> m;
	m+= make_pair(1,"one"),make_pair(2,"two");
	insert(m)(1,"one")(2,"two");
	return 0;
	
}

 初始化和重复填充数据

#include <iostream>
#include <vector>
#include <string>
#include <set>
#include <map>
#include <boost/assign.hpp>
using namespace std;
using namespace boost::assign;


int main()
{
	//初始化代码
	vector<int> v = list_of(1)(2)(3);
	map<int,string> m = map_list_of(1,"one")(2,"two");
	//重复数据
	vector<int> vrepeat = list_of(1).repeat(3,10)(2)(3);
	return 0;
	
}

 3.由于交换时需要进行拷贝和赋值,如果是对象很大会产生很大的运行时代价。所以需要高效的交换函数。

4.operators是用于重载操作符的类,是一系列的类,有两大特点,一是采用友元,二是自动推导

4.1.equality_comparable 要求提供==可自动实现!=

4.2.less_than_comparable:要求提供<,可自动实现>.<=.>=

4.3.addable:要求提供+=可自动实现+

#include <iostream>
#include <boost/operators.hpp>
using namespace std;
using namespace boost;

class Point:boost::less_than_comparable<Point>
{
public:
	Point(int x = 0,int y = 0,int z = 0):m_x(x),m_y(y),m_z(z){}
	friend bool operator<(const Point& l,const Point& r)
	{
		return (l.m_x *l.m_x < r.m_x * r.m_x);
	}
private:
	int m_x;
	int m_y;
	int m_z;
};
int main()
{
	Point lp(1,2,3);
	Point rp(3,4,5);
	if (rp>=lp)
	{
		cout << "your test is right"<<endl;
	}
	
}

 

posted @ 2013-08-15 23:17  l851654152  阅读(392)  评论(0编辑  收藏  举报