for_each.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*=============================================================================
  2. Copyright (c) 2001-2011 Joel de Guzman
  3. Copyright (c) 2018 Kohei Takahashi
  4. Distributed under the Boost Software License, Version 1.0. (See accompanying
  5. file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. ==============================================================================*/
  7. #include <boost/core/lightweight_test.hpp>
  8. #include <boost/fusion/container/vector/vector.hpp>
  9. #include <boost/fusion/adapted/mpl.hpp>
  10. #include <boost/fusion/sequence/io/out.hpp>
  11. #include <boost/fusion/sequence/comparison/equal_to.hpp>
  12. #include <boost/fusion/algorithm/iteration/for_each.hpp>
  13. #include <boost/mpl/vector_c.hpp>
  14. struct print
  15. {
  16. template <typename T>
  17. void operator()(T const& v) const
  18. {
  19. std::cout << "[ " << v << " ] ";
  20. }
  21. };
  22. struct increment
  23. {
  24. template <typename T>
  25. void operator()(T& v) const
  26. {
  27. ++v;
  28. }
  29. };
  30. struct mutable_increment : increment
  31. {
  32. template <typename T>
  33. void operator()(T& v)
  34. {
  35. return increment::operator()(v);
  36. }
  37. };
  38. int
  39. main()
  40. {
  41. using namespace boost::fusion;
  42. using boost::mpl::vector_c;
  43. namespace fusion = boost::fusion;
  44. {
  45. typedef vector<int, char, double, char const*> vector_type;
  46. vector_type v(1, 'x', 3.3, "Ruby");
  47. for_each(v, print());
  48. std::cout << std::endl;
  49. }
  50. {
  51. char const ruby[] = "Ruby";
  52. typedef vector<int, char, double, char const*> vector_type;
  53. vector_type v(1, 'x', 3.3, ruby);
  54. for_each(v, increment());
  55. BOOST_TEST_EQ(v, vector_type(2, 'y', 4.3, ruby + 1));
  56. std::cout << v << std::endl;
  57. }
  58. {
  59. char const ruby[] = "Ruby";
  60. typedef vector<int, char, double, char const*> vector_type;
  61. vector_type v(1, 'x', 3.3, ruby);
  62. for_each(v, mutable_increment());
  63. BOOST_TEST_EQ(v, vector_type(2, 'y', 4.3, ruby + 1));
  64. std::cout << v << std::endl;
  65. }
  66. {
  67. typedef vector_c<int, 2, 3, 4, 5, 6> mpl_vec;
  68. fusion::for_each(mpl_vec(), print());
  69. std::cout << std::endl;
  70. }
  71. return boost::report_errors();
  72. }