fork(1) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. template <typename ...Funcs>
  5. struct overload_set;
  6.  
  7. template <typename Head, typename ...Tail>
  8. struct overload_set<Head, Tail...> : Head, overload_set < Tail... >
  9. {
  10. overload_set(Head head, Tail... tail)
  11. : Head(head)
  12. , overload_set < Tail... > (tail...)
  13. {}
  14.  
  15. using Head::operator();
  16. using overload_set<Tail...>::operator();
  17. };
  18.  
  19. template <typename Func>
  20. struct overload_set<Func> : Func
  21. {
  22. overload_set(Func func)
  23. : Func(func)
  24. {}
  25.  
  26. using Func::operator();
  27. };
  28.  
  29. template <typename ...Funcs>
  30. overload_set<Funcs...> overload(Funcs... funcs)
  31. {
  32. return overload_set < Funcs... > (funcs...);
  33. }
  34.  
  35. int main()
  36. {
  37. auto f = overload(
  38. [] { return 1; }, // 1
  39. [](int x) { return x + 1; }, // 2
  40. [](double x) { return 2 * x; } // 3
  41. );
  42.  
  43. using std::cout;
  44. using std::endl;
  45. cout << f() << endl // call 1
  46. << f(1) << endl // call 2
  47. << f(2.0) << endl; // call 3
  48.  
  49. return 0;
  50. }
Success #stdin #stdout 0s 3096KB
stdin
Standard input is empty
stdout
1
2
4