fork(114) 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. visit_at(tup, 0, doSomething);
  40. }
Success #stdin #stdout 0s 3096KB
stdin
Standard input is empty
stdout
a