Guest User

Untitled

a guest
Nov 18th, 2017
142
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <functional>
  4. #include <string>
  5.  
  6. using param_type = const std::string &;
  7.  
  8. std::string call(const std::function<std::string(param_type)> &func, param_type str)
  9. {
  10. std::string result = func(str);
  11. std::cout << result << std::endl;
  12. return result;
  13. }
  14.  
  15. std::string greet_function(param_type str) {
  16. return "Hello from function " + str;
  17. }
  18.  
  19. struct GreetFunctor {
  20. const std::string greet;
  21. GreetFunctor(std::string greet): greet(std::move(greet)) {}
  22.  
  23. std::string operator()(param_type str) { return greet + " " + str; }
  24. };
  25.  
  26.  
  27. struct Greet{
  28. const std::string greet;
  29. Greet(std::string greet): greet(std::move(greet)) {}
  30.  
  31. std::string greet_me(param_type str) { return greet + " " + str; }
  32. };
  33.  
  34. /* Out of scope */
  35.  
  36. // advanced version
  37. template<typename func_t>
  38. std::string templated_call(func_t func, param_type str)
  39. {
  40. std::string result = func(str);
  41. std::cout << result << std::endl;
  42. return result;
  43. }
  44.  
  45.  
  46. // ultra hyper advanced
  47. template<typename func_t, typename param_t>
  48. auto auto_call(func_t func, param_t str)
  49. {
  50. auto result = func(str);
  51. std::cout << result << std::endl;
  52. return result;
  53. }
  54.  
  55. int main()
  56. {
  57. call([](param_type name){ return "Hello from lambda " + name; }, "Peter");
  58. call(GreetFunctor("Hello from functor human"), "Peter");
  59. call(greet_function, "Peter");
  60.  
  61.  
  62. Greet greet("Hello from method pointer");
  63. call(std::bind(&Greet::greet_me, &greet, std::placeholders::_1), "Peter");
  64.  
  65. std::cout << std::endl << "Templated version:" << std::endl;
  66. templated_call([](param_type name){ return "Hello from lambda " + name; }, "Peter");
  67. templated_call(GreetFunctor("Hello from functor human"), "Peter");
  68. templated_call(greet_function, "Peter");
  69.  
  70. std::cout << std::endl << "Auto version:" << std::endl;
  71. auto_call([](param_type name){ return "Hello from lambda " + name; }, "Peter");
  72. auto_call(GreetFunctor("Hello from functor human"), "Peter");
  73. auto_call(greet_function, "Peter");
  74. return 0;
  75. }
Add Comment
Please, Sign In to add comment