generic_stringize.cpp 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright Antony Polukhin, 2013-2019.
  2. // Distributed under the Boost Software License, Version 1.0.
  3. // (See the accompanying file LICENSE_1_0.txt
  4. // or a copy at <http://www.boost.org/LICENSE_1_0.txt>.)
  5. #include <boost/config.hpp>
  6. #ifdef BOOST_MSVC
  7. # pragma warning(disable: 4512) // generic_stringize.cpp(37) : warning C4512: 'stringize_functor' : assignment operator could not be generated
  8. #endif
  9. //[lexical_cast_stringize
  10. /*`
  11. In this example we'll make a `stringize` method that accepts a sequence, converts
  12. each element of the sequence into string and appends that string to the result.
  13. Example is based on the example from the [@http://www.packtpub.com/boost-cplusplus-application-development-cookbook/book Boost C++ Application Development Cookbook]
  14. by Antony Polukhin, ISBN 9781849514880.
  15. Step 1: Making a functor that converts any type to a string and remembers result:
  16. */
  17. #include <boost/lexical_cast.hpp>
  18. struct stringize_functor {
  19. private:
  20. std::string& result;
  21. public:
  22. explicit stringize_functor(std::string& res)
  23. : result(res)
  24. {}
  25. template <class T>
  26. void operator()(const T& v) const {
  27. result += boost::lexical_cast<std::string>(v);
  28. }
  29. };
  30. //` Step 2: Applying `stringize_functor` to each element in sequence:
  31. #include <boost/fusion/include/for_each.hpp>
  32. template <class Sequence>
  33. std::string stringize(const Sequence& seq) {
  34. std::string result;
  35. boost::fusion::for_each(seq, stringize_functor(result));
  36. return result;
  37. }
  38. //` Step 3: Using the `stringize` with different types:
  39. #include <cassert>
  40. #include <boost/fusion/adapted/boost_tuple.hpp>
  41. #include <boost/fusion/adapted/std_pair.hpp>
  42. int main() {
  43. boost::tuple<char, int, char, int> decim('-', 10, 'e', 5);
  44. assert(stringize(decim) == "-10e5");
  45. std::pair<int, std::string> value_and_type(270, "Kelvin");
  46. assert(stringize(value_and_type) == "270Kelvin");
  47. }
  48. //] [/lexical_cast_stringize]