]>
Commit | Line | Data |
---|---|---|
f51cf556 | 1 | // Copyright Antony Polukhin, 2013-2023. |
7c673cae FG |
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 | ||
b32b8144 FG |
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 | |
7c673cae FG |
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] | |
1e59de90 | 18 | by Antony Polukhin, ISBN 9781849514880. Russian translation: [@https://dmkpress.com/catalog/computer/programming/c/978-5-97060-868-5/ ISBN: 9785970608685]. |
7c673cae FG |
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: | |
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> | |
42 | template <class Sequence> | |
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: | |
7c673cae FG |
50 | #include <boost/fusion/adapted/boost_tuple.hpp> |
51 | #include <boost/fusion/adapted/std_pair.hpp> | |
52 | ||
53 | int main() { | |
54 | boost::tuple<char, int, char, int> decim('-', 10, 'e', 5); | |
f67539c2 TL |
55 | if (stringize(decim) != "-10e5") { |
56 | return 1; | |
57 | } | |
7c673cae | 58 | |
b32b8144 | 59 | std::pair<int, std::string> value_and_type(270, "Kelvin"); |
f67539c2 TL |
60 | if (stringize(value_and_type) != "270Kelvin") { |
61 | return 2; | |
62 | } | |
63 | ||
64 | return 0; | |
7c673cae FG |
65 | } |
66 | ||
67 | //] [/lexical_cast_stringize] | |
68 | ||
69 | ||
70 |