array_of_template.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // Copyright (c) 2008 Joseph Gauterin, Niels Dekker
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt or copy at
  5. // http://www.boost.org/LICENSE_1_0.txt)
  6. // Tests swapping an array of swap_test_template<int> objects by means of boost::swap.
  7. #include <boost/utility/swap.hpp>
  8. #include <boost/core/lightweight_test.hpp>
  9. #define BOOST_CHECK BOOST_TEST
  10. #define BOOST_CHECK_EQUAL BOOST_TEST_EQ
  11. //Put test class in the global namespace
  12. #include "./swap_test_class.hpp"
  13. #include <algorithm> //for std::copy and std::equal
  14. #include <cstddef> //for std::size_t
  15. template <class T>
  16. class swap_test_template
  17. {
  18. public:
  19. typedef T template_argument;
  20. swap_test_class swap_test_object;
  21. };
  22. template <class T>
  23. inline bool operator==(const swap_test_template<T> & lhs, const swap_test_template<T> & rhs)
  24. {
  25. return lhs.swap_test_object == rhs.swap_test_object;
  26. }
  27. template <class T>
  28. inline bool operator!=(const swap_test_template<T> & lhs, const swap_test_template<T> & rhs)
  29. {
  30. return !(lhs == rhs);
  31. }
  32. //Provide swap function in the namespace of swap_test_template
  33. //(which is the global namespace). Note that it isn't allowed to put
  34. //an overload of this function within the std namespace.
  35. template <class T>
  36. void swap(swap_test_template<T>& left, swap_test_template<T>& right)
  37. {
  38. left.swap_test_object.swap(right.swap_test_object);
  39. }
  40. int main()
  41. {
  42. const std::size_t array_size = 2;
  43. const swap_test_template<int> initial_array1[array_size] = { swap_test_class(1), swap_test_class(2) };
  44. const swap_test_template<int> initial_array2[array_size] = { swap_test_class(3), swap_test_class(4) };
  45. swap_test_template<int> array1[array_size];
  46. swap_test_template<int> array2[array_size];
  47. std::copy(initial_array1, initial_array1 + array_size, array1);
  48. std::copy(initial_array2, initial_array2 + array_size, array2);
  49. swap_test_class::reset();
  50. boost::swap(array1, array2);
  51. BOOST_CHECK(std::equal(array1, array1 + array_size, initial_array2));
  52. BOOST_CHECK(std::equal(array2, array2 + array_size, initial_array1));
  53. BOOST_CHECK_EQUAL(swap_test_class::swap_count(), array_size);
  54. BOOST_CHECK_EQUAL(swap_test_class::copy_count(), 0);
  55. return boost::report_errors();
  56. }