fork(1) download
  1. #include <functional>
  2. #include <utility>
  3. #include <iterator>
  4. #include <memory>
  5. #include <set>
  6. #include <iostream>
  7. #include <vector>
  8.  
  9. template<typename T>
  10. struct for_each_helper_interface {
  11. virtual ~for_each_helper_interface() {}
  12. virtual void for_each( std::function< void(T) > const& ) = 0;
  13. };
  14. template<typename C, typename T>
  15. struct for_each_helper:for_each_helper_interface<T> {
  16. C& c;
  17. for_each_helper( C& in ):c(in) {}
  18. virtual void for_each( std::function< void(T) > const& f ) override final {
  19. for( auto&& x:c ) {
  20. f(x);
  21. }
  22. }
  23. };
  24. template<typename T>
  25. struct for_each_adaptor {
  26. std::unique_ptr<for_each_helper_interface<T>> pImpl;
  27. void for_each( std::function< void(T) > const& f ) {
  28. if (pImpl) {
  29. pImpl->for_each(f);
  30. }
  31. }
  32. template<typename C>
  33. for_each_adaptor( C&& c ): pImpl( new for_each_helper<C, T>( std::forward<C>(c) ) ) {}
  34. };
  35. void print_stuff( for_each_adaptor<std::string const&> c ) {
  36. c.for_each([&](std::string const&s){
  37. std::cout << s << "\n";
  38. });
  39. }
  40. int main() {
  41. std::set<std::string> s;
  42. s.insert("hello");
  43. s.insert("world");
  44. print_stuff(s);
  45. std::vector<std::string> v;
  46. v.push_back("hola");
  47. v.push_back("bola");
  48. print_stuff(v);
  49. }
  50.  
  51.  
  52.  
  53.  
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
hello
world
hola
bola