introduction.cpp 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright Louis Dionne 2013-2017
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
  4. // Make sure `assert` always triggers an assertion
  5. #ifdef NDEBUG
  6. # undef NDEBUG
  7. #endif
  8. #include <boost/fusion/include/comparison.hpp>
  9. #include <boost/fusion/include/make_vector.hpp>
  10. #include <boost/fusion/include/transform.hpp>
  11. #include <boost/fusion/include/vector.hpp>
  12. #include <boost/mpl/equal.hpp>
  13. #include <boost/mpl/placeholders.hpp>
  14. #include <boost/mpl/transform.hpp>
  15. #include <boost/mpl/vector.hpp>
  16. #include <algorithm>
  17. #include <cassert>
  18. #include <iterator>
  19. #include <sstream>
  20. #include <string>
  21. #include <vector>
  22. namespace fusion = boost::fusion;
  23. namespace mpl = boost::mpl;
  24. using namespace std::literals;
  25. int main() {
  26. {
  27. //! [runtime]
  28. auto f = [](int i) -> std::string {
  29. return std::to_string(i * i);
  30. };
  31. std::vector<int> ints{1, 2, 3, 4};
  32. std::vector<std::string> strings;
  33. std::transform(ints.begin(), ints.end(), std::back_inserter(strings), f);
  34. assert((strings == std::vector<std::string>{"1", "4", "9", "16"}));
  35. //! [runtime]
  36. }{
  37. //! [heterogeneous]
  38. auto to_string = [](auto t) {
  39. std::stringstream ss;
  40. ss << t;
  41. return ss.str();
  42. };
  43. fusion::vector<int, std::string, float> seq{1, "abc", 3.4f};
  44. fusion::vector<std::string, std::string, std::string>
  45. strings = fusion::transform(seq, to_string);
  46. assert(strings == fusion::make_vector("1"s, "abc"s, "3.4"s));
  47. //! [heterogeneous]
  48. }
  49. }
  50. //! [type-level]
  51. template <typename T>
  52. struct add_const_pointer {
  53. using type = T const*;
  54. };
  55. using types = mpl::vector<int, char, float, void>;
  56. using pointers = mpl::transform<types, add_const_pointer<mpl::_1>>::type;
  57. static_assert(mpl::equal<
  58. pointers,
  59. mpl::vector<int const*, char const*, float const*, void const*>
  60. >::value, "");
  61. //! [type-level]