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