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)
8 * \file util_dynamic_type_disp.cpp
9 * \author Andrey Semashev
12 * \brief This header contains tests for the dynamic type dispatcher.
15 #define BOOST_TEST_MODULE util_dynamic_type_disp
18 #include <boost/bind.hpp>
19 #include <boost/test/unit_test.hpp>
20 #include <boost/test/tools/floating_point_comparison.hpp>
21 #include <boost/log/utility/type_dispatch/dynamic_type_dispatcher.hpp>
23 namespace logging = boost::log;
27 // A simple attribute value
28 template< typename T >
33 explicit my_value(T const& value) : m_Value(value) {}
35 // The function passes the contained type into the dispatcher
36 bool dispatch(logging::type_dispatcher& dispatcher)
38 logging::type_dispatcher::callback< T > callback = dispatcher.get_callback< T >();
59 my_visitor() : m_Expected(none_expected), m_Int(0), m_Double(0.0) {}
63 m_Expected = none_expected;
65 void set_expected(int value)
67 m_Expected = int_expected;
70 void set_expected(double value)
72 m_Expected = double_expected;
75 void set_expected(std::string const& value)
77 m_Expected = string_expected;
81 // Implement visitation logic for all supported types
82 void on_int(int const& value)
84 BOOST_CHECK_EQUAL(m_Expected, int_expected);
85 BOOST_CHECK_EQUAL(m_Int, value);
87 void on_double(double const& value)
89 BOOST_CHECK_EQUAL(m_Expected, double_expected);
90 BOOST_CHECK_CLOSE(m_Double, value, 0.001);
92 void on_string(std::string const& value)
94 BOOST_CHECK_EQUAL(m_Expected, string_expected);
95 BOOST_CHECK_EQUAL(m_String, value);
99 type_expected m_Expected;
102 std::string m_String;
107 // The test checks that general functionality works
108 BOOST_AUTO_TEST_CASE(type_dispatch)
111 logging::dynamic_type_dispatcher disp;
113 // Register type visitors
114 disp.register_type< int >(boost::bind(&my_visitor::on_int, &vis, _1));
115 disp.register_type< double >(boost::bind(&my_visitor::on_double, &vis, _1));
117 BOOST_CHECK(disp.registered_types_count() == 2);
119 // Right now strings are not supported by the dispatcher
120 my_value< std::string > val1("Hello world!");
121 BOOST_CHECK(!val1.dispatch(disp));
124 disp.register_type< std::string >(boost::bind(&my_visitor::on_string, &vis, _1));
125 BOOST_CHECK(disp.registered_types_count() == 3);
127 vis.set_expected(val1.m_Value);
128 BOOST_CHECK(val1.dispatch(disp));
130 my_value< double > val2(1.2);
131 vis.set_expected(val2.m_Value);
132 BOOST_CHECK(val2.dispatch(disp));
134 // This one is not supported
135 my_value< float > val3(static_cast< float >(-4.3));
137 BOOST_CHECK(!val3.dispatch(disp));