fork download
  1. #include <vector>
  2. #include <algorithm>
  3. #include <functional>
  4. #include <iostream>
  5. #include <typeinfo>
  6. #include <string>
  7. #include <memory>
  8. #include <cxxabi.h>
  9.  
  10. template <class T>
  11. std::string type_name()
  12. {
  13. typedef typename std::remove_reference<T>::type TR;
  14. std::unique_ptr<char, void(*)(void*)> own
  15. (
  16. abi::__cxa_demangle(typeid(TR).name(), nullptr,
  17. nullptr, nullptr),
  18. std::free
  19. );
  20. std::string r = own != nullptr?own.get():typeid(TR).name();
  21. if (std::is_const<TR>::value)
  22. r += " const";
  23. if (std::is_volatile<TR>::value)
  24. r += " volatile";
  25. if (std::is_lvalue_reference<T>::value)
  26. r += " &";
  27. else if (std::is_rvalue_reference<T>::value)
  28. r += " &&";
  29. return r;
  30. }
  31.  
  32. template<class InputIt, class UnaryFunction>
  33. UnaryFunction for_every(InputIt first, InputIt last, UnaryFunction f)
  34. {
  35. std::cout << "Calling callable object of type ";
  36. std::cout << type_name<UnaryFunction>() << ".\n";
  37. for (; first != last; ++first)
  38. {
  39. f(*first);
  40. }
  41. std::cout << "\n";
  42. return f;
  43. }
  44.  
  45. void d_to_cout(double const v) { std::cout << v; }
  46. void d_to_cout_sep(double const v, char const sep) { std::cout << v << sep; }
  47.  
  48. struct d_printer
  49. {
  50. bool first = true;
  51. void operator () (double const v)
  52. {
  53. if (!first) std::cout << ", ";
  54. std::cout << v;
  55. first = false;
  56. }
  57. };
  58.  
  59.  
  60. int main()
  61. {
  62. std::vector<double> const a{ 1.0, 2.0, 3.0 };
  63. for_every(a.begin(), a.end(), &d_to_cout);
  64. for_every(a.begin(), a.end(), std::function<void(double const)>(d_to_cout));
  65. for_every(a.begin(), a.end(), d_printer());
  66. for_every(a.begin(), a.end(), &d_to_cout);
  67. for_every(a.begin(), a.end(), [](double const v) {
  68. std::cout << v;
  69. });
  70. for_every(a.begin(), a.end(), std::bind(
  71. d_to_cout_sep, std::placeholders::_1, '/'
  72. ));
  73. return 0;
  74. }
Success #stdin #stdout 0s 3232KB
stdin
Standard input is empty
stdout
Calling callable object of type void (*)(double).
123
Calling callable object of type std::function<void (double)>.
123
Calling callable object of type d_printer.
1, 2, 3
Calling callable object of type void (*)(double).
123
Calling callable object of type main::{lambda(double)#1}.
123
Calling callable object of type std::_Bind<void (*(std::_Placeholder<1>, char))(double, char)>.
1/2/3/