fork(1) download
  1. #include<tuple>
  2. #include<type_traits>
  3. #include<string>
  4. #include<iostream>
  5.  
  6. template<bool b, typename T=void>
  7. using EnableIf = typename std::enable_if<b,T>::type;
  8.  
  9. template<int Index, template<typename T>class Search, int Which, typename, class First, class... Types>
  10. struct get_internal:
  11. get_internal<Index + 1, Search, Which, void, Types...>
  12. {};
  13.  
  14. template<int Index, template<typename T>class Search, int Which, class First, class... Types>
  15. struct get_internal<Index, Search, Which, EnableIf<!Search<First>::value>, First, Types...>:
  16. get_internal<Index + 1, Search, Which, void, Types...>
  17. {};
  18. template<int Index, template<typename T>class Search, int Which, class First, class... Types>
  19. struct get_internal<Index, Search, Which, EnableIf<Search<First>::value>, First, Types...>:
  20. get_internal<Index + 1, Search, Which-1, void, Types...>
  21. {};
  22. template<int Index, template<typename T>class Search, class First, class... Types>
  23. struct get_internal<Index, Search, 0, EnableIf<Search<First>::value>, First, Types...>:
  24. std::integral_constant<int, Index>
  25. {
  26. typedef get_internal type;
  27. };
  28.  
  29. template<template<typename>class Test, int Which=0, class... Types>
  30. auto get(std::tuple<Types...> tuple)->
  31. decltype(std::get<get_internal<0,Test,Which,void,Types...>::value>(tuple))
  32. {
  33. return std::get<get_internal<0,Test,Which,void,Types...>::value>(tuple);
  34. }
  35.  
  36. template<typename T>
  37. struct is_type {
  38. template<typename U>
  39. using test = std::is_same<T,U>;
  40. };
  41.  
  42. template<class T, int Which=0, class... Types>
  43. T get(std::tuple<Types...> tuple)
  44. {
  45. return get<is_type<T>::template test,Which>(tuple);
  46. }
  47.  
  48. int main()
  49. {
  50. std::tuple<int, double, std::string, int, long> test{1, 1.7, "test", 7, 3};
  51. std::cout<<"get<0> == get<int> :"<< (std::get<0>(test) == get<int>(test))<< "\n";
  52. std::cout<<"get<3> == get<int,1> :"<< (std::get<3>(test) == get<int,1>(test))<< "\n";
  53. std::cout<<"get<1> == get<double> :"<<(std::get<1>(test) == get<double>(test))<< "\n";
  54. std::cout<<"get<2> == get<std::string> :"<<(std::get<2>(test) == get<std::string>(test))<< "\n";
  55. std::cout<<"get<0> == get<std::is_integral> :"<< (std::get<0>(test) == get<std::is_integral>(test))<< "\n";
  56. std::cout<<"get<3> == get<std::is_integral,1> :"<< (std::get<3>(test) == get<std::is_integral,1>(test))<< "\n";
  57. std::cout<<"get<4> == get<std::is_integral,2> :"<< (std::get<4>(test) == get<std::is_integral,2>(test))<< "\n";
  58. }
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
get<0> == get<int> :1
get<3> == get<int,1> :1
get<1> == get<double> :1
get<2> == get<std::string> :1
get<0> == get<std::is_integral> :1
get<3> == get<std::is_integral,1> :1
get<4> == get<std::is_integral,2> :1