运行期以索引获取tuple元素-C++14(原创)

  在编译期很容易根据索引来获取对应位置的元素,因为 tuple 的帮助函数 std::get<N>(tp) 就能获取 tuple 中第 N 个元素。然而我们却不能直接在运行期通过变量来获取 tuple 中的元素值,比如下面的用法:

int i  =  0; 
std::get<i>(tp); 

  这样写是不合法的,会报一个需要编译期常量的错误。 要通过运行时的变最米获取 tuple 中的元素值,需要采取一些替代手法,将运行期变量“映射”为编译期常量。

  下面是基于C++14实现的,运行期以索引获取tuple元素的方法。需支持C++14及以上标准的编译器,VS2017 15.5.x、CodeBlocks 16.01 gcc 7.2。

//运行期以索引获取tuple元素-C++14(原创)
//需支持C++14及以上标准的编译器,VS2017 15.5.x、CodeBlocks 16.01 gcc 7.2

#include <iostream>
#include <tuple>
#include <utility>  //index_sequence
using namespace std;

template <typename Tuple>
void visit3(size_t i, Tuple& tup, index_sequence<>)
{
}

template <typename Tuple, size_t... Idx>
void visit3(size_t i, Tuple& tp, index_sequence<Idx...>)
{
    constexpr size_t I = index_sequence<Idx...>::size() - 1;
    if (i == I)
        cout << get<I>(tp) << endl;
  else
     visit3(i, tp, make_index_sequence<I>{});
}

template <typename Tuple>
void visit_help(size_t i, Tuple& tp)
{
    visit3(i, tp, make_index_sequence<tuple_size<Tuple>::value>{});
}

int main()
{
    auto tp = make_tuple(45, "The test", true);
    int i = 0;
    visit_help(i, tp);  //45

    return 0;
}

 

posted on 2017-12-23 18:08  patton88  阅读(676)  评论(0编辑  收藏  举报

导航