C++11 std::tuple

一 简介

头文件 <tuple>

template< class... Types >
class tuple; (C++11)

二 取值及辅助函数

#include <functional>  // tie
#include <iostream>    // cout cin
#include <tuple>       // tuple

int main() {
  {
    // 取值
    std::tuple<int, double> t{1, 1.1};
    std::cout << "std::get<0>(t): " << std::get<0>(t) << std::endl;
    std::cout << "std::get<1>(t): " << std::get<1>(t) << std::endl;
  }
  {
    // 辅助函数
    // tie ignore
    int i = 0;
    double d = 0;
    std::tuple<int, double> t{1, 2.2};
    std::tie(i, d) = t;
    std::tie(std::ignore, i) = t;
    std::cout << "i: " << i << " d: " << d << std::endl;

    // make_tuple ref
    auto m = std::make_tuple(3, 4);
    int i1 = 0;
    double d1 = 0;
    auto m1 = std::make_tuple(std::ref(i1), d1);
    std::get<1>(m1) = 100; // i1 = 100

    // tuple_element
    using Type = std::tuple_element<0, decltype(m)>::type;  // int
    Type e = 100;

    // tuple_cat
    auto c = std::tuple_cat(t, m);

    // tuple_size
    std::cout << "std::tuple_size<decltype(c)>::value: "
              << std::tuple_size<decltype(c)>::value << std::endl;
  }
  std::cin.get();
}

三 tuple打印

template <int Index, int Size, typename ...Args>
class PrintTuple{
 public:
  static void print(std::ostream& os, const std::tuple<Args...>& t) {
    os << std::get<Index>(t) << ((Index + 1 == Size) ? " " : ", ");
    PrintTuple<Index + 1, Size, Args...>::print(os, t);
  }
};

template <int Size, typename... Args>
class PrintTuple<Size, Size, Args...> {
 public:
  static void print(std::ostream& os, const std::tuple<Args...>& t) {
  }
};

template <typename ...Args>
std::ostream& operator<<(std::ostream& os, const std::tuple<Args...>& t) {
  os << "[";
  PrintTuple<0, sizeof...(Args), Args...>::print(os, t);
  os << "]";
  return os;
}


// main
auto m = std::make_tuple(1, 2, "hello");
std::cout << "m: " << m;

两段代码结果:

四 参考

cppreference

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值