C++ tuple 速记

来源:互联网 发布:淘宝优惠券怎么赚钱 编辑:程序博客网 时间:2024/05/22 19:43

简介

tuple 是C++11 以模板的形式开发的元组, 类似于pair , 但是支持任意的元素个数。

基本的操作

int main (){    /*** Construct a tuple ***/    // By constrcut     std::tuple<int,char> foo (10,'x');    // By make_tuple    auto bar = std::make_tuple ("test", 3.1, 14, 'y');    // By forward_as_tuple    auto ref = std::forward_as_tuple(std::string("test") + "eee" , 1, 'a');    /*** Assign ***/    std::get<2>(bar) = 100;    /*** Get type and get value ***/    std::tuple_element<0,decltype(bar)>::type bar_1 = std::get<0>(bar);    /*** unpack a tuple ***/    int myint; char mychar;    std::tie (myint, mychar) = foo;                            // unpack elements    std::tie (std::ignore, std::ignore, myint, mychar) = bar;  // unpack (with ignore)    /*** get size as a type **/    std::cout << std::tuple_size<decltype(bar)>::value << "\n";    auto merge = std::tuple_cat(foo,bar);    return 0;}

可以看到 , tuple的构造是比较灵活的, 可以提前声明具体实例化类型, 也可以交由编译器根据构造
参数推导。

forward_as_tuple似的tuple对右值有较好的支持。
std::tiestd::ignorestd::get 之外提供了获取tuple内部元素的方式,且
支持批量获取。

在将一个tuple视为一种特定类型的时候 :
tuple_element 提供了获取对应元素的类型的途径。
tuple_size 提供了获取tuple类型大小的途径。

std::tuple_cat 提供了合并tuple为一个tuple的途径
尚未有截断tuple的直接接口。

0 0