alfps

silly hack

May 11th, 2012
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.50 KB | None | 0 0
  1. #include <algorithm>        // std::sort
  2. #include <iostream>         // std::cout
  3. #include <iterator>         // output_iterator
  4. #include <utility>          // std::begin, std::end
  5. #include <vector>           // std::vector
  6. using namespace std;
  7.  
  8. template< class ResultCollection, class C >
  9. ResultCollection create( C const& c )
  10. { return ResultCollection( begin( c ), end( c ) ); }
  11.  
  12. template< class Type >
  13. class Ref
  14. {
  15. private:
  16.     Type*   p_;
  17.  
  18. public:
  19.     Type& ref() const { return *p_; }
  20.  
  21.     Ref( Type& r ): p_( &r ) {}
  22. };
  23.  
  24. template< class Type >
  25. Ref< Type > ref( Type& r ) { return Ref< Type >( r ); }
  26.  
  27.  
  28. template< class C, class... Args >
  29. class With
  30. {
  31. private:
  32.     Ref< C >  c_;
  33.  
  34. public:
  35.     typedef decltype( begin( declval<C&>() ) )   Iter;
  36.  
  37.     void operator()( void f( Iter, Iter, Args... ), Args&&... args )
  38.     { return f( begin( c_.ref() ), end( c_.ref() ), forward( args )... ); }
  39.  
  40.     template< class OutIter >
  41.     OutIter operator()(
  42.         OutIter f( Iter, Iter, OutIter, Args... ),
  43.         OutIter const outIt,
  44.         Args&&... args
  45.         )
  46.     { return f( begin( c_.ref() ), end( c_.ref() ), outIt, forward( args )... ); }
  47.    
  48.     With( C& c )
  49.         : c_( c )
  50.     {}
  51. };
  52.  
  53. template< class C >
  54. With< C > with( C& c ) { return With< C >( c ); }
  55.  
  56. int main()
  57. {
  58.     int const   data[]  = {3, 1, 4, 1, 5, 9, 2, 6, 5, 4};
  59.  
  60.     auto v = create< vector< int > >( data );
  61.  
  62.     with( v )( sort );
  63.     with( v )( copy, ostream_iterator<int>( cout, " " ) );
  64. }
Add Comment
Please, Sign In to add comment