my_vector_example.cpp 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. // Boost.Assign library
  2. //
  3. // Copyright Thorsten Ottosen 2003-2004. Use, modification and
  4. // distribution is subject to the Boost Software License, Version
  5. // 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt)
  7. //
  8. // For more information, see http://www.boost.org/libs/assign/
  9. //
  10. #include <boost/detail/workaround.hpp>
  11. #if BOOST_WORKAROUND(__BORLANDC__, BOOST_TESTED_AT(0x564))
  12. # pragma warn -8091 // suppress warning in Boost.Test
  13. # pragma warn -8057 // unused argument argc/argv in Boost.Test
  14. #endif
  15. #include <boost/assign/list_inserter.hpp>
  16. #include <boost/test/test_tools.hpp>
  17. #include <boost/function.hpp>
  18. #include <boost/bind.hpp>
  19. #include <vector>
  20. #include <stdexcept>
  21. namespace ba = boost::assign;
  22. template< class C >
  23. class range_inserter
  24. {
  25. typedef typename C::iterator iterator;
  26. iterator begin, end;
  27. public:
  28. range_inserter( C& c )
  29. : begin( c.begin() ), end( c.end() )
  30. { }
  31. template< class T >
  32. void operator()( T r )
  33. {
  34. if( begin == end )
  35. throw std::range_error( "range error: <range_inserter>" );
  36. *begin = r;
  37. ++begin;
  38. }
  39. };
  40. template< class C >
  41. inline range_inserter<C> make_range_inserter( C& c )
  42. {
  43. return range_inserter<C>( c );
  44. }
  45. template< class T >
  46. class my_vector
  47. {
  48. typedef std::vector<T> vector_t;
  49. typedef typename vector_t::size_type size_type;
  50. vector_t data_;
  51. public:
  52. my_vector() : data_( 10, 0 )
  53. { }
  54. ba::list_inserter< range_inserter< vector_t >, T >
  55. operator=( T r )
  56. {
  57. return ba::make_list_inserter( make_range_inserter( data_ ) )( r );
  58. }
  59. size_type size() const
  60. {
  61. return data_.size();
  62. }
  63. const T& operator[]( size_type index )
  64. {
  65. return data_.at( index );
  66. }
  67. };
  68. void check_list_inserter()
  69. {
  70. using namespace std;
  71. using namespace boost::assign;
  72. my_vector<int> vec;
  73. vec = 1,2,3,4,5,6,7,8,9,10;
  74. BOOST_CHECK_EQUAL( vec.size(), 10u );
  75. BOOST_CHECK_EQUAL( vec[0], 1 );
  76. BOOST_CHECK_EQUAL( vec[9], 10 );
  77. }
  78. #include <boost/test/unit_test.hpp>
  79. using boost::unit_test::test_suite;
  80. test_suite* init_unit_test_suite( int argc, char* argv[] )
  81. {
  82. test_suite* test = BOOST_TEST_SUITE( "List Test Suite" );
  83. test->add( BOOST_TEST_CASE( &check_list_inserter ) );
  84. return test;
  85. }