C++编程

C++编程 - tuple、any容器


flyfish 2014-10-29


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

作用1 替换struct

struct t1
{
int nID;
double dVal;
};

替换为
typedef std::tuple<int,double> t1;


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

std::tuple<int,double> TupleFunction1()
{
	std::tuple<int,double> tupRet(0,0);


	tupRet=std::tuple<int,double>(1,2.1);


	return tupRet;
}


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


调用
auto ret=TupleFunction1();
 std::cout<<std::get<0>(ret)<<" "<<std::get<1>(ret)<< std::endl;

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

借助any建造一种能够存储随意类型且大小动态变化的容器
	 std::vector<boost::any> 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<int>(a)<<std::endl;
		}
		if(a.type() == typeid(double))
		{
			std::cout<< boost::any_cast<double>(a)<<std::endl;
		}


	}
}

函数调用
for each(auto e in v)
{
	OutputAny(e);
}




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

原文地址:https://www.cnblogs.com/tlnshuju/p/6733134.html