fork(8) download
  1. // Test1.cpp: определяет точку входа для консольного приложения.
  2. //
  3. #include <memory>
  4. #include <utility>
  5. #include <functional>
  6.  
  7. template <typename T>
  8. struct Callable;
  9.  
  10. template <typename R, typename... Args>
  11. struct Callable <R(Args...)>
  12. {
  13. virtual R operator () (Args&&...) {}
  14. };
  15.  
  16. template <typename T>
  17. class Function;
  18.  
  19. template <typename R, typename... Args>
  20. class Function<R(Args...)>
  21. {
  22. typedef std::unique_ptr <Callable<R(Args...)>> Ptr;
  23. Ptr ptr;
  24.  
  25. template <typename T>
  26. class Realisation : public Callable<R(Args...)>
  27. {
  28. T t;
  29. public :
  30. R operator () (Args&&... args)
  31. {
  32. return t(std::forward<Args>(args)...);
  33. }
  34.  
  35. Realisation () {}
  36.  
  37. Realisation(T&& at) : t(std::move(at))
  38. {}
  39. };
  40.  
  41. public :
  42. R operator () (Args&&... args)
  43. {
  44. return ptr->operator () (std::forward<Args>(args)...);
  45. }
  46.  
  47. Function ()
  48. {}
  49.  
  50. template <typename T>
  51. Function (T&& t): ptr(std::make_unique<Realisation<T>>(std::move(t)))
  52. {}
  53. };
  54.  
  55. int main()
  56. {
  57. Function<void(const char*)> f = [] (const char* a) { printf("%s\n", a); };
  58. f("Hello, world!");
  59.  
  60. getchar();
  61. return 0;
  62. }
  63.  
  64.  
Success #stdin #stdout 0s 3416KB
stdin
Standard input is empty
stdout
Hello, world!