1、tuple
tuple是由代表由任意类型组成的东西,类似pair是由两种元素组成。
1)tuple的结构G4.8
解析:
a、模板类tuple由泛化和特化版本组成。其中特化版本类的模板参数由Head和多个Tail组成,可以将tuple参数拆分为第一个和后面一组;
b、特化版本类继承本身,但模板参数是去掉首元素Head;
c、在tuple中的数据是m_head,代表模板参数中的首元素;
所以当声明类tuple后,如下:
解析:
a、其中head()函数返回首参数;
b、其中tail()函数返回后面模板参数组成的tuple;
tuple的继承结构实现如下:
说明:根据tuple的继承本身的结构,将上述例子进行分解,每个父类代表含有后一个元素的tuple。
2)示例
#include <string>
using std::string;
#include <complex>
#include <iostream>
using namespace std;
#include <tuple>
int _tmain(int argc, _TCHAR* argv[])
{//可以由任意类型组成
cout << "string, sizeof " << sizeof(int) << endl; //4
cout << "double, sizeof " << sizeof(double) << endl; //8
cout << "complext, sizeof " << sizeof(complex<double>) << endl; //16
tuple<int, double, std::complex<double>> t;
cout << sizeof(t) << endl; //32
tuple<int, float, string> t1(41, 6.3, "nice");
cout << sizeof(t1) << endl; //36
cout << "t1: " << get<0>(t1) << " " << get<1>(t1) << " " << get<2>(t1) << endl; //#1
auto t2 = make_tuple(22, 44, "stacy");
cout << "t2: " << get<0>(t2) << " " << get<1>(t2) << " " << get<2>(t2) << endl;
if (t1 < t2){ //#2
cout << "t1 < t2" << endl;
}
else if (t1 > t2){
cout << "t1 > t2" << endl;
}
else{
cout << "t1 = t2" << endl;
}
typedef tuple<int, float, string> TupleType; //#3
cout << tuple_size<TupleType>::value << endl; //3
return 0;
}
解析:
a、如#1,标准库中定义了获取tuple数据的方法get<位置>(tuple对象);
b、如#2,标准库中对tuple进行了一部分的操作符重载;
c、如#3,可以使用tuple_size<...>::value方法计算tuple中的元素的个数;
2、type traits
1)可以通过type traits的设计来判断对象如是否有构造函数,是否有拷贝构造,是否有拷贝赋值等等。如下为C++11用法:
属性判断:
主要类型判断:
复合类型判断:
类型特征:
2)用例
template<typename T>
void type_traits_output(const T& x){
cout << "is_class\t" << is_class<T>::value << endl;
cout << "is_const\t" << is_const<T>::value << endl;
}
int _tmain(int argc, _TCHAR* argv[])
{
complex<double> c(1, 2);
type_traits_output(c);
return 0;
}
/*
is_class 1
is_const 0
*/
说明:通过type_traits来判断复数comlex,可知comlex是一个类class,但不是const。