for_each.cpp 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // Copyright Aleksey Gurtovoy 2000-2004
  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. //
  7. // See http://www.boost.org/libs/mpl for documentation.
  8. // $Id$
  9. // $Date$
  10. // $Revision$
  11. #include <boost/mpl/for_each.hpp>
  12. #include <boost/mpl/list.hpp>
  13. #include <boost/mpl/range_c.hpp>
  14. #include <boost/mpl/identity.hpp>
  15. #include <boost/mpl/lambda.hpp>
  16. #include <boost/bind.hpp>
  17. #include <vector>
  18. #include <iostream>
  19. #include <algorithm>
  20. #include <typeinfo>
  21. #include <cassert>
  22. namespace mpl = boost::mpl;
  23. struct type_printer
  24. {
  25. type_printer(std::ostream& s) : f_stream(&s) {}
  26. template< typename U > void operator()(mpl::identity<U>)
  27. {
  28. *f_stream << typeid(U).name() << '\n';
  29. }
  30. private:
  31. std::ostream* f_stream;
  32. };
  33. struct value_printer
  34. {
  35. value_printer(std::ostream& s) : f_stream(&s) {}
  36. template< typename U > void operator()(U x)
  37. {
  38. *f_stream << x << '\n';
  39. }
  40. private:
  41. std::ostream* f_stream;
  42. };
  43. #ifdef __ICL
  44. # pragma warning(disable:985)
  45. #endif
  46. void push_back(std::vector<int>* c, int i)
  47. {
  48. c->push_back(i);
  49. }
  50. int main()
  51. {
  52. typedef mpl::list<char,short,int,long,float,double> types;
  53. mpl::for_each< types,mpl::make_identity<mpl::_1> >(type_printer(std::cout));
  54. typedef mpl::range_c<int,0,10> numbers;
  55. std::vector<int> v;
  56. mpl::for_each<numbers>(
  57. boost::bind(&push_back, &v, _1)
  58. );
  59. mpl::for_each< numbers >(value_printer(std::cout));
  60. for (unsigned i = 0; i < v.size(); ++i)
  61. assert(v[i] == (int)i);
  62. return 0;
  63. }