fork(2) download
  1. #include <iostream>
  2. #include <map>
  3. #include <type_traits>
  4. #include <utility>
  5.  
  6. using namespace std;
  7.  
  8. struct one {
  9. int foo(const int) { return 0; }
  10. int bar() { return 0; }
  11. };
  12.  
  13. struct two {
  14. int foo(const int) { return 1; }
  15. };
  16.  
  17. struct three {
  18. int foo(const int) { return 2; }
  19. int bar() { return 2; }
  20. };
  21.  
  22. struct owner {
  23. map<int, one> ones;
  24. map<int, two> twos;
  25. map<int, three> threes;
  26.  
  27. template <typename ... Ts>
  28. struct overload {};
  29.  
  30. template <typename T>
  31. struct overload<T> : T
  32. {
  33. template <typename U>
  34. overload(U&& u) : T(std::forward<U>(u)) {}
  35.  
  36. using T::operator();
  37. };
  38.  
  39.  
  40. template <typename T, typename ... Ts>
  41. struct overload<T, Ts...> : overload<T>, overload<Ts...>
  42. {
  43. template <typename U, typename ... Us>
  44. overload(U&& arg, Us&&... args) : overload<T>(std::forward<U>(arg)), overload<Ts...>(std::forward<Us>(args)...) {}
  45.  
  46. using overload<T>::operator();
  47. using overload<Ts...>::operator();
  48. };
  49.  
  50. template<class... Ts>
  51. overload<std::decay_t<Ts>...> make_overload(Ts&&... args)
  52. {
  53. return { std::forward<Ts>(args)... };
  54. }
  55.  
  56. struct fallback_t { template<class T> fallback_t(T&&) {} };
  57.  
  58. template <typename T, typename Func>
  59. int callFunc(T& param, const Func& func) {
  60. return func(param);
  61. }
  62.  
  63. template <typename T>
  64. int findObject(int key, const T& func) {
  65. if(ones.count(key) != 0U) {
  66. return callFunc(ones[key], func);
  67. }
  68. else if(twos.count(key) != 0U) {
  69. return callFunc(twos[key], func);
  70. }
  71. else {
  72. return callFunc(threes[key], func);
  73. }
  74. }
  75.  
  76. int foo(const int key, const int param) { return findObject(key, [&](auto& value) { return value.foo(param); }); }
  77. int bar(const int key) {
  78. return findObject(key, make_overload(
  79. [](const auto& value) -> decltype(fooint(value.bar())) { return value.bar(); },
  80. [](fallback_t){ std::cout << "fallback\n"; return 13; }
  81. ));
  82. }
  83. };
  84.  
  85. int main() {
  86. owner myOwner;
  87.  
  88. myOwner.ones.insert(make_pair(0, one()));
  89. myOwner.twos.insert(make_pair(1, two()));
  90. myOwner.threes.insert(make_pair(2, three()));
  91.  
  92. myOwner.foo(2, 1);
  93. cout << myOwner.bar(1) << endl;
  94. cout << myOwner.bar(2) << endl;
  95. }
Success #stdin #stdout 0s 4480KB
stdin
Standard input is empty
stdout
fallback
13
fallback
13