C++ 11 新特性总结(五):tuple元组类型
元组类型
C++越来越往Python方向靠近,以致习惯上回到纯C的时代开始使人无比痛苦。
是的,C++
11引入了元组支持,支持将任意数量的类型封装成单一对象,且在C++
17引入了auto[x,y,z] = t
简单的解包方法;tuple
没有size
和type
成员,需要std::tuple_size
和std::tuple_element
结合类型推导或萃取来获取大小和类型,以下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
using namespace std;
int main(){
//构造方式一:
std::tuple<int, std::string, double> mytuple(0, "Eden", 1.2);
//解包:
cout << std::get<0>(mytuple) << std::get<1>(mytuple) << std::get<2>(mytuple) <<endl;
//构造方式二:
auto t = std::make_tuple<int, std::string, double>(0,"Mike", 2.0);
//C++ 17解包:
auto[x,y,z] = t;
cout << x << y <<z;
//大小、类型
constexpr size_t size = std::tuple_size<decltype(mytuple)>::value;
using firstType = std::tuple_element<0, decltype(mytuple)>::type;
cout << std::is_same_v<firstType, int> <<endl;
cout <<size <<endl;
return 0;
}