fork(2) download
  1. #include <cstddef>
  2. #include <functional>
  3. #include <iostream>
  4. #include <sstream>
  5. #include <stdexcept>
  6. #include <string>
  7. #include <vector>
  8.  
  9. template<std::size_t... Is>
  10. struct index_sequence
  11. { };
  12.  
  13. template<std::size_t N, std::size_t... Is>
  14. struct make_index_sequence : make_index_sequence<N - 1, N - 1, Is...>
  15. { };
  16.  
  17. template<std::size_t... Is>
  18. struct make_index_sequence<0, Is...> : index_sequence<Is...>
  19. { };
  20.  
  21. template<typename T>
  22. T unstring(std::string const& s)
  23. {
  24. std::stringstream ss(s);
  25. T result;
  26. if (!(ss >> result)) {
  27. throw std::logic_error("Cannot convert T into a string");
  28. }
  29. return result;
  30. }
  31.  
  32. template<typename R, typename... Args>
  33. class wrapped
  34. {
  35. public:
  36. explicit
  37. wrapped(R (&func)(Args...))
  38. : func_(func)
  39. {
  40. }
  41.  
  42. public:
  43. std::string operator()(std::vector<std::string> args)
  44. {
  45. if (sizeof...(Args) != args.size()) {
  46. throw std::logic_error("Incorrect number of arguments");
  47. }
  48.  
  49. auto const& result = invoke(make_index_sequence<sizeof...(Args)>(),
  50. args);
  51. using std::to_string;
  52. return to_string(result);
  53. }
  54.  
  55. private:
  56. template<std::size_t... Is>
  57. R invoke(index_sequence<Is...>, std::vector<std::string> const& args)
  58. {
  59. return func_((unstring<Args>)(args[Is])...);
  60. }
  61.  
  62. private:
  63. R (*func_)(Args...);
  64. };
  65.  
  66. template<typename R, typename... Args>
  67. std::function<std::string (std::vector<std::string>)>
  68. wrap(R (&func)(Args...))
  69. {
  70. return wrapped<R, Args...>(func);
  71. }
  72.  
  73. int add(int const x, int const y)
  74. {
  75. return x + y;
  76. }
  77.  
  78. int main()
  79. {
  80. auto const f = wrap(add);
  81. std::cout << f({"1", "2"});
  82. }
  83.  
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
3