C++编程 - tuple、any容器
C++编程 - tuple、any容器flyfish 2014-10-29一 tupletuple是固定大小的容器,每个元素类型可以不同作用1 替换structstruct t1{int nID;double dVal;};替换为typedef std::tuple t1;作用2 任意个数的函数返回值写法1std::tup
·
C++编程 - tuple、any容器
flyfish 2014-10-29
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下编译通过
更多推荐
已为社区贡献3条内容
所有评论(0)