]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
1 | // Copyright 2013 Antony Polukhin |
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 | ||
8 | //[lexical_cast_stringize | |
9 | /*` | |
10 | In this example we'll make a `stringize` method that accepts a sequence, converts | |
11 | each element of the sequence into string and appends that string to the result. | |
12 | ||
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 | ||
16 | Step 1: Making a functor that converts any type to a string and remembers result: | |
17 | */ | |
18 | ||
19 | #include <boost/lexical_cast.hpp> | |
20 | ||
21 | struct stringize_functor { | |
22 | private: | |
23 | std::string& result; | |
24 | ||
25 | public: | |
26 | explicit stringize_functor(std::string& res) | |
27 | : result(res) | |
28 | {} | |
29 | ||
30 | template <class T> | |
31 | void operator()(const T& v) const { | |
32 | result += boost::lexical_cast<std::string>(v); | |
33 | } | |
34 | }; | |
35 | ||
36 | //` Step 2: Applying `stringize_functor` to each element in sequence: | |
37 | #include <boost/fusion/include/for_each.hpp> | |
38 | template <class Sequence> | |
39 | std::string stringize(const Sequence& seq) { | |
40 | std::string result; | |
41 | boost::fusion::for_each(seq, stringize_functor(result)); | |
42 | return result; | |
43 | } | |
44 | ||
45 | //` Step 3: Using the `stringize` with different types: | |
46 | #include <cassert> | |
47 | #include <boost/fusion/adapted/boost_tuple.hpp> | |
48 | #include <boost/fusion/adapted/std_pair.hpp> | |
49 | ||
50 | int main() { | |
51 | boost::tuple<char, int, char, int> decim('-', 10, 'e', 5); | |
52 | assert(stringize(decim) == "-10e5"); | |
53 | ||
54 | std::pair<short, std::string> value_and_type(270, "Kelvin"); | |
55 | assert(stringize(value_and_type) == "270Kelvin"); | |
56 | } | |
57 | ||
58 | //] [/lexical_cast_stringize] | |
59 | ||
60 | ||
61 |