fork download
  1. #include <utility>
  2. #include <cstdio>
  3. #include <cmath>
  4.  
  5. template<typename Fn>
  6. class Action {
  7. Fn* function_ptr;
  8.  
  9. public:
  10. Action() noexcept : function_ptr(nullptr) {
  11. }
  12. Action(std::nullptr_t) noexcept : function_ptr(nullptr) {
  13. }
  14. Action(const Action& other) : function_ptr(other.function_ptr) {
  15. }
  16. Action(Fn f) : function_ptr(f) {
  17. }
  18.  
  19. Action& operator=(const Action& other) {
  20. return (function_ptr = other.function_ptr, *this);
  21. }
  22. Action& operator=(std::nullptr_t ) {
  23. return (function_ptr = nullptr, *this);
  24. }
  25. Action& operator=(Fn f) {
  26. return (function_ptr = f, *this);
  27. }
  28.  
  29. template<typename... Params>
  30. auto operator()(Params&&... params) {
  31. return function_ptr(std::forward<Params>(params)...);
  32. }
  33. };
  34.  
  35. void test(int i) {
  36. printf("The given parameter is: %d\n", i);
  37. }
  38.  
  39. int main() {
  40. Action<decltype(printf)> pf_1;
  41. pf_1 = nullptr;
  42. pf_1 = printf;
  43.  
  44. Action<decltype(printf)> pf_2(pf_1);
  45. pf_2("The value of Pi is: %.5f\n", M_PI);
  46.  
  47. Action<decltype(test)> test_fn(test);
  48. test_fn(12);
  49.  
  50. return 0;
  51. }
Success #stdin #stdout 0s 16064KB
stdin
Standard input is empty
stdout
The value of Pi is: 3.14159
The given parameter is: 12