fork download
  1. #include <tuple>
  2. #include <cassert>
  3. #include <iostream>
  4.  
  5. template <size_t I>
  6. struct visit_impl
  7. {
  8. template <typename T, typename F>
  9. static void visit(T& tup, size_t idx, F fun)
  10. {
  11. if (idx == I - 1) fun(std::get<I - 1>(tup));
  12. else visit_impl<I - 1>::visit(tup, idx, fun);
  13. }
  14. };
  15.  
  16. template <>
  17. struct visit_impl<0>
  18. {
  19. template <typename T, typename F>
  20. static void visit(T& tup, size_t idx, F fun) { assert(false); }
  21. };
  22.  
  23. template <typename F, typename... Ts>
  24. void visit_at(std::tuple<Ts...> const& tup, size_t idx, F fun)
  25. {
  26. visit_impl<sizeof...(Ts)>::visit(tup, idx, fun);
  27. }
  28.  
  29. template <typename F, typename... Ts>
  30. void visit_at(std::tuple<Ts...>& tup, size_t idx, F fun)
  31. {
  32. visit_impl<sizeof...(Ts)>::visit(tup, idx, fun);
  33. }
  34.  
  35. int main()
  36. {
  37. auto tup = std::make_tuple('a', 42, 13.37);
  38. auto doSomething = [](auto v) { std::cout << v << "\n"; };
  39. int n(0);
  40. std::cin >> n;
  41. visit_at(tup, n, doSomething);
  42. }
Success #stdin #stdout 0s 5284KB
stdin
2
stdout
13.37