util_static_type_disp.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. #include <cassert>
  8. #include <cstddef>
  9. #include <string>
  10. #include <iostream>
  11. #include <boost/mpl/vector.hpp>
  12. #include <boost/log/utility/type_dispatch/static_type_dispatcher.hpp>
  13. namespace logging = boost::log;
  14. //[ example_util_static_type_dispatcher
  15. // Base interface for the custom opaque value
  16. struct my_value_base
  17. {
  18. virtual ~my_value_base() {}
  19. virtual bool dispatch(logging::type_dispatcher& dispatcher) const = 0;
  20. };
  21. // A simple attribute value
  22. template< typename T >
  23. struct my_value :
  24. public my_value_base
  25. {
  26. T m_value;
  27. explicit my_value(T const& value) : m_value(value) {}
  28. // The function passes the contained type into the dispatcher
  29. bool dispatch(logging::type_dispatcher& dispatcher) const
  30. {
  31. logging::type_dispatcher::callback< T > cb = dispatcher.get_callback< T >();
  32. if (cb)
  33. {
  34. cb(m_value);
  35. return true;
  36. }
  37. else
  38. return false;
  39. }
  40. };
  41. // Value visitor for the supported types
  42. struct print_visitor
  43. {
  44. typedef void result_type;
  45. // Implement visitation logic for all supported types
  46. void operator() (int const& value) const
  47. {
  48. std::cout << "Received int value = " << value << std::endl;
  49. }
  50. void operator() (double const& value) const
  51. {
  52. std::cout << "Received double value = " << value << std::endl;
  53. }
  54. void operator() (std::string const& value) const
  55. {
  56. std::cout << "Received string value = " << value << std::endl;
  57. }
  58. };
  59. // Prints the supplied value
  60. bool print(my_value_base const& val)
  61. {
  62. typedef boost::mpl::vector< int, double, std::string > types;
  63. print_visitor visitor;
  64. logging::static_type_dispatcher< types > disp(visitor);
  65. return val.dispatch(disp);
  66. }
  67. //]
  68. int main(int, char*[])
  69. {
  70. // These two attributes are supported by the dispatcher
  71. bool res = print(my_value< std::string >("Hello world!"));
  72. assert(res);
  73. res = print(my_value< double >(1.2));
  74. assert(res);
  75. // This one is not
  76. res = print(my_value< float >(-4.3f));
  77. assert(!res);
  78. return 0;
  79. }