首页 > 编程语言 > 详细

C++编程 - tuple、any容器

时间:2014-10-29 21:32:19      阅读:276      评论:0      收藏:0      [点我收藏+]

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下编译通过

C++编程 - tuple、any容器

原文:http://blog.csdn.net/flyfish1986/article/details/40593089

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!