fork(2) download
  1. #include <iostream>
  2. #include <memory>
  3. #include <tuple>
  4.  
  5. struct Base { };
  6. struct A : Base { A(int) {} ~A() { std::cout << "~A\n"; } };
  7. struct B : Base { B(int) {} ~B() { std::cout << "~B\n"; } };
  8. struct C : Base { C(int) {} ~C() { std::cout << "~C\n"; } };
  9.  
  10. template<int... Is>
  11. struct indices { typedef indices type; };
  12.  
  13. template<int N, int... Is>
  14. struct make_indices : make_indices<N - 1, N - 1, Is...> { };
  15.  
  16. template<int... Is>
  17. struct make_indices<0, Is...> : indices<Is...> { };
  18.  
  19. template<typename... Types>
  20. struct Factory
  21. {
  22. typedef std::tuple<Types...> TypesTuple;
  23.  
  24. std::shared_ptr<Base> operator()(int const index)
  25. {
  26. return produce(index);
  27. }
  28.  
  29. std::shared_ptr<Base> produce(int const index)
  30. {
  31. return produce_impl(make_indices<sizeof...(Types)>(), index);
  32. }
  33.  
  34. template<int I, int... Is>
  35. std::shared_ptr<Base> produce_impl(indices<I, Is...>, int const index)
  36. {
  37. if (I == index) {
  38. return std::make_shared<typename std::tuple_element<I, TypesTuple>::type>(42);
  39. }
  40.  
  41. return produce_impl(indices<Is...>(), index);
  42. }
  43.  
  44. std::shared_ptr<Base> produce_impl(indices<>, int const index)
  45. {
  46. throw "Uh-oh!";
  47. }
  48. };
  49.  
  50. int main()
  51. {
  52. Factory<A, B, C> fac;
  53. fac(0);
  54. fac(1);
  55. fac(2);
  56. fac(3); // cause exception.
  57. }
  58.  
Runtime error #stdin #stdout #stderr 0s 3476KB
stdin
Standard input is empty
stdout
~A
~B
~C
stderr
terminate called after throwing an instance of 'char const*'