C++ tuple模板类使用体验
tuple类可以说是一种特殊的pair类型,其内部可以最大包含10个左右不同类型的成员(pair只能包含两个)
使用tuple需要包含头文件
对应std::make_pair,tuple也有对应的std::make_tuple模板函数用于创建特定类型的tuple对象
tuple主要有如下常用的操作
make_tuple
make_tuple用于创建一个指定类型的tuple对象,例如std::make_tuple<int, float, std::string>
get
get函数是一个模板函数,用法是get<N(0~10)>(tuple类型对象),模板参数是一个下标索引,标识想要获取tuple对象中的第几个成员。
另外,由于get是一个模板函数,因此无法使用for循环调用get来获取tuple类型对象中的每一个成员(因为需要编译期就确定模板参数,for的循环下标在编译期无法确定)
tie
tie用于将一些变量临时绑定称为一个tuple对象,即tuple<type1&, type2&,…> obj = tie(type1 obj1, type2 ,…);
下面这个例子说明了上面三个tuple操作的使用:
#include <iostream>
#include <tuple>
#include <string>
using namespace std;
int main(int argc, void* argv[])
{
tuple<int, string> studentInfo = make_tuple(3, "lcb");
cout<<"student number is:"<<get<0>(studentInfo)<<", name is:"<<get<1>(studentInfo)<<endl;
cout<<"tuple size is:"<<tuple_size<decltype(studentInfo)>::value<<endl;
int randomInt = 22;
string randomStr = "fuXk";
float randomFloat = 0.112;
tuple<int, string, float> tieObject = tie(randomInt, randomStr, randomFloat);
cout<<"tie object:"<<get<0>(tieObject)<<","<<get<1>(tieObject)<<","<<get<2>(tieObject)<<endl;
getchar();
}