fork download
  1. #include <type_traits>
  2. #include <memory>
  3. #include <iterator>
  4. #include <algorithm>
  5. #include <iostream>
  6. #include <iomanip>
  7. #include <vector>
  8. #include <list>
  9.  
  10. template < typename ALLOCATOR, typename T >
  11. using rebind_to_type = typename std::allocator_traits<ALLOCATOR>::template rebind_alloc<T> ;
  12.  
  13. template < typename ALLOCATOR, typename FN, typename T >
  14. using rebind_to_result_type = rebind_to_type< ALLOCATOR, typename std::result_of< FN(T) >::type > ;
  15.  
  16. template < typename U, typename T, typename A, template<typename,typename> class CONTAINER >
  17. CONTAINER< U, rebind_to_type<A,U> > adapt( const CONTAINER<T,A>& c )
  18. { return CONTAINER< U, rebind_to_type<A,U> >( c.begin(), c.end() ) ; }
  19.  
  20. template < typename T, typename A, template<typename,typename> class CONTAINER, typename FN >
  21. CONTAINER< typename std::result_of< FN(T) >::type, rebind_to_result_type<A,FN,T> >
  22. adapt( const CONTAINER<T,A>& c, FN fn )
  23. {
  24. CONTAINER< typename std::result_of< FN(T) >::type, rebind_to_result_type<A,FN,T> > result ;
  25. std::transform( c.begin(), c.end(), std::back_inserter(result), fn ) ;
  26. return result ;
  27. }
  28.  
  29. int main()
  30. {
  31. std::cout << std::fixed << std::showpoint << std::setprecision(2) ;
  32.  
  33. std::vector<int> vec { 64, 74, 77, 87, 58, 58, 75, 87 } ;
  34. for( auto i : vec ) std::cout << i << ' ' ;
  35. std::cout << '\n' ;
  36.  
  37. // implicit conversion int to double => std::vector<int> => std::vector<double>
  38. auto vec2 = adapt<double>(vec) ;
  39. for( auto d : vec2 ) std::cout << d << ' ' ;
  40. std::cout << '\n' ;
  41.  
  42. std::list<short> lst( vec.rbegin(), vec.rend() ) ;
  43. for( auto s : lst ) std::cout << s << ' ' ;
  44. std::cout << '\n' ;
  45.  
  46. // explicit transformation short to double => std::list<short> => std::list<double>
  47. auto lst2 = adapt( lst, [] ( int v ) { return v*v / 100.0 ; } ) ;
  48. for( auto d : lst2 ) std::cout << d << ' ' ;
  49. std::cout << '\n' ;
  50.  
  51. struct base { int i ; }; struct offset { int i ; }; struct derived : offset, base {} ;
  52. std::vector<derived*> vec3 { new derived, new derived, new derived } ;
  53. for( auto p : vec3 ) std::cout << p << ' ' ;
  54. std::cout << '\n' ;
  55.  
  56. // implicit conversion derived* to base* => std::vector<base*> => std::vector<derived*>
  57. std::vector<base*> vec4 = adapt<base*>(vec3) ;
  58. for( auto p : vec4 ) std::cout << p << ' ' ;
  59. std::cout << '\n' ;
  60. }
  61.  
Success #stdin #stdout 0s 2988KB
stdin
Standard input is empty
stdout
64 74 77 87 58 58 75 87 
64.00 74.00 77.00 87.00 58.00 58.00 75.00 87.00 
87 75 58 58 87 77 74 64 
75.69 56.25 33.64 33.64 75.69 59.29 54.76 40.96 
0x8c8d1b8 0x8c8d1c8 0x8c8d1d8 
0x8c8d1bc 0x8c8d1cc 0x8c8d1dc