util_dynamic_type_disp.cpp 2.2 KB

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