运行期以索引获取tuple元素-C++17

2017-12-24 10:19:24来源:cnblogs.com作者:patton88人点击

分享
//运行期以索引获取tuple元素-C++17//需支持C++17及以上标准的编译器,VS2017 15.5.x、CodeBlocks 16.01 gcc 7.2//参见:http://purecpp.org/?p=1581#include <iostream>#include <tuple>using namespace std;template <size_t Idx, typename T>void visit(T& tup, size_t i){    if (i == Idx)        cout << get<Idx>(tup) << endl;}//template <typename Tuple, size_t... Idx>//void visit(size_t i, Tuple& tp, index_sequence<Idx...>)//{//    (visit<Idx>(tp, i), ...);//}template <class Tuple, size_t...Idx>void visit1(size_t i, Tuple& tp, index_sequence<Idx...>){    ((i == Idx && (visit<Idx>(tp, i), false)), ...);}template <typename Tuple>void visit_help(size_t i, Tuple& tp){    //visit(i, tp, make_index_sequence<tuple_size<Tuple>::value>{});    visit1(i, tp, make_index_sequence<tuple_size<Tuple>::value>{});}int main(){    auto tp = make_tuple(45, "The test", true);    int i = 1;    visit_help(i, tp);  //The test    return 0;}

微信扫一扫

第七城市微信公众平台