]>
Commit | Line | Data |
---|---|---|
7c673cae FG |
1 | /* |
2 | * Copyright Andrey Semashev 2007 - 2015. | |
3 | * Distributed under the Boost Software License, Version 1.0. | |
4 | * (See accompanying file LICENSE_1_0.txt or copy at | |
5 | * http://www.boost.org/LICENSE_1_0.txt) | |
6 | */ | |
7 | ||
8 | #include <cassert> | |
9 | #include <cstddef> | |
10 | #include <string> | |
11 | #include <iostream> | |
12 | #include <boost/mpl/vector.hpp> | |
13 | #include <boost/log/utility/type_dispatch/static_type_dispatcher.hpp> | |
14 | ||
15 | namespace logging = boost::log; | |
16 | ||
17 | //[ example_util_static_type_dispatcher | |
18 | // Base interface for the custom opaque value | |
19 | struct my_value_base | |
20 | { | |
21 | virtual ~my_value_base() {} | |
22 | virtual bool dispatch(logging::type_dispatcher& dispatcher) const = 0; | |
23 | }; | |
24 | ||
25 | // A simple attribute value | |
26 | template< typename T > | |
27 | struct my_value : | |
28 | public my_value_base | |
29 | { | |
30 | T m_value; | |
31 | ||
32 | explicit my_value(T const& value) : m_value(value) {} | |
33 | ||
34 | // The function passes the contained type into the dispatcher | |
35 | bool dispatch(logging::type_dispatcher& dispatcher) const | |
36 | { | |
37 | logging::type_dispatcher::callback< T > cb = dispatcher.get_callback< T >(); | |
38 | if (cb) | |
39 | { | |
40 | cb(m_value); | |
41 | return true; | |
42 | } | |
43 | else | |
44 | return false; | |
45 | } | |
46 | }; | |
47 | ||
48 | // Value visitor for the supported types | |
49 | struct print_visitor | |
50 | { | |
51 | typedef void result_type; | |
52 | ||
53 | // Implement visitation logic for all supported types | |
54 | void operator() (int const& value) const | |
55 | { | |
56 | std::cout << "Received int value = " << value << std::endl; | |
57 | } | |
58 | void operator() (double const& value) const | |
59 | { | |
60 | std::cout << "Received double value = " << value << std::endl; | |
61 | } | |
62 | void operator() (std::string const& value) const | |
63 | { | |
64 | std::cout << "Received string value = " << value << std::endl; | |
65 | } | |
66 | }; | |
67 | ||
68 | // Prints the supplied value | |
69 | bool print(my_value_base const& val) | |
70 | { | |
71 | typedef boost::mpl::vector< int, double, std::string > types; | |
72 | ||
73 | print_visitor visitor; | |
74 | logging::static_type_dispatcher< types > disp(visitor); | |
75 | ||
76 | return val.dispatch(disp); | |
77 | } | |
78 | //] | |
79 | ||
80 | int main(int, char*[]) | |
81 | { | |
82 | // These two attributes are supported by the dispatcher | |
83 | bool res = print(my_value< std::string >("Hello world!")); | |
84 | assert(res); | |
85 | ||
86 | res = print(my_value< double >(1.2)); | |
87 | assert(res); | |
88 | ||
89 | // This one is not | |
90 | res = print(my_value< float >(-4.3f)); | |
91 | assert(!res); | |
92 | ||
93 | return 0; | |
94 | } |