5.1.1 Pair
Class pair可将两个value视为一个单元,准确的说是Struct pair,定义与头文件<utility>中:
namspace std { template<typename T1,typename T2> struct pair{ T1 fisrt, T2 second }; }
比较简单的操作就不介绍了,写几个比较少用的。
pair<T1,T2> p(piecewise_construct,t1,t2) |
建立一个pair,元素类型分别为tuple T1,T2,以tuple t1和t2的元素为初值。 |
get<0>(p) | get<0>是一个模板函数,得到pair first的值 |
get<1>(p) | 得到second的值 |
std::tuple_size(P)::value | 得到pair的大小 |
std::tuple_element<0,P>::type | 得到first的类型 |
其中分段构造(piecewise_construct)是只能用于tuple,将tuple中的元素拆开来构造
如下例子:
class Foo { public: Foo(tuple<int, float>) { cout << "foo::foo(tuple)" << endl; } template<typename... Args> Foo(Args... args) { cout << "foo::(args..)" << endl; } }; int main() { tuple<int, float> t(1, 2.22); pair<int, Foo> p1(42, t); pair<int, Foo> p2(piecewise_construct, make_tuple(42), t); system("pause"); return 0; }
输出如下:
因为指定了分段构造,所以t被拆开,所以有多个参数。注意:这种情况只能用于tuple。