1// Copyright Antony Polukhin, 2013-2024.
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. Russian translation: [@https://dmkpress.com/catalog/computer/programming/c/978-5-97060-868-5/ ISBN: 9785970608685].
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
25struct stringize_functor {
26private:
27 std::string& result;
28
29public:
30 explicit stringize_functor(std::string& res)
31 : result(res)
32 {}
33
34 template <class T>
35 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>
42template <class Sequence>
43std::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/std_tuple.hpp>
51#include <boost/fusion/adapted/std_pair.hpp>
52
53int main() {
54 std::tuple<char, int, char, int> decim('-', 10, 'e', 5);
55 if (stringize(seq: decim) != "-10e5") {
56 return 1;
57 }
58
59 std::pair<int, std::string> value_and_type(270, "Kelvin");
60 if (stringize(seq: value_and_type) != "270Kelvin") {
61 return 2;
62 }
63
64 return 0;
65}
66
67//] [/lexical_cast_stringize]
68
69
70
71

source code of boost/libs/lexical_cast/example/generic_stringize.cpp