C++编程 - tuple、any容器

2015-01-27 14:02:31 · 作者: · 浏览: 23

C++编程 - tuple、any容器


flyfish 2014-10-29


一 tuple
tuple是固定大小的容器,每个元素类型可以不同

作用1 替换struct

struct t1
{
int nID;
double dVal;
};

替换为
typedef std::tuple
  
    t1;
  


作用2 任意个数的函数返回值
写法1

std::tuple
  
    TupleFunction1()
{
	std::tuple
   
     tupRet(0,0); tupRet=std::tuple
    
     (1,2.1); return tupRet; }
    
   
  


写法2
std::tuple
  
    TupleFunction2()
{
	return std::make_tuple(1,2.1);
}
  


调用
auto ret=TupleFunction1();
 std::cout<
  
   (ret)<<" "<
   
    (ret)<< std::endl;
   
  

二 any
any容器采用boost库中的any
boost::any 只存储一个任意类型的元素
boost::any a=1;
boost::any b=2.1;

借助any建造一种可以存储任意类型且大小动态变化的容器
	 std::vector
  
    v;
	 v.push_back(1);
	 v.push_back(2.1);
  


输出函数
void OutputAny(boost::any a)
{
	if (!a.empty())
	{
		if(a.type() == typeid(int))
		{
			std::cout<< boost::any_cast
  
   (a)<
   
    (a)<
    
     
函数调用
for each(auto e in v)
{
	OutputAny(e);
}




以上程序在Visual C++2010下编译通过