fork(1) download
  1. #include <iostream>
  2. #include <string>
  3. #include <stdexcept>
  4. #include <functional>
  5. #include <utility>
  6.  
  7. template <typename... Args, typename F, size_t... ints>
  8. void match_impl(size_t n, const std::tuple<Args...>& t, const F& f, std::integer_sequence<size_t, ints...> int_seq)
  9. {
  10. std::function<void()> fs[sizeof...(Args)] = {
  11. [&]() { f(std::get<ints>(t)); }...
  12. };
  13.  
  14. fs[n]();
  15. }
  16.  
  17. template <typename... Args, typename F>
  18. void match(size_t n, const std::tuple<Args...>& t, const F& f )
  19. {
  20. match_impl(n, t, f, std::index_sequence_for<Args...>{});
  21. }
  22.  
  23. int main() {
  24. auto tuple = std::make_tuple(1, '2', 3.33, std::string("abcdef"));
  25.  
  26. int tuple_index = 3;
  27.  
  28. auto visitor = [](const auto& tuple_value) {
  29. std::cout << tuple_value << std::endl;
  30. };
  31.  
  32. match(tuple_index, tuple, visitor);
  33.  
  34. return 0;
  35. }
Success #stdin #stdout 0s 4528KB
stdin
Standard input is empty
stdout
abcdef