C++ tuple 速记

简介

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值