last_value.hpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // last_value function object (documented as part of Boost.Signals)
  2. // Copyright Frank Mori Hess 2007.
  3. // Copyright Douglas Gregor 2001-2003. Use, modification and
  4. // distribution is subject to the Boost Software License, Version
  5. // 1.0. (See accompanying file LICENSE_1_0.txt or copy at
  6. // http://www.boost.org/LICENSE_1_0.txt)
  7. // For more information, see http://www.boost.org
  8. #ifndef BOOST_SIGNALS2_LAST_VALUE_HPP
  9. #define BOOST_SIGNALS2_LAST_VALUE_HPP
  10. #include <boost/optional.hpp>
  11. #include <boost/signals2/expired_slot.hpp>
  12. #include <boost/throw_exception.hpp>
  13. #include <stdexcept>
  14. namespace boost {
  15. namespace signals2 {
  16. // no_slots_error is thrown when we are unable to generate a return value
  17. // due to no slots being connected to the signal.
  18. class no_slots_error: public std::exception
  19. {
  20. public:
  21. virtual const char* what() const throw() {return "boost::signals2::no_slots_error";}
  22. };
  23. template<typename T>
  24. class last_value {
  25. public:
  26. typedef T result_type;
  27. template<typename InputIterator>
  28. T operator()(InputIterator first, InputIterator last) const
  29. {
  30. if(first == last)
  31. {
  32. boost::throw_exception(no_slots_error());
  33. }
  34. optional<T> value;
  35. while (first != last)
  36. {
  37. try
  38. {
  39. value = *first;
  40. }
  41. catch(const expired_slot &) {}
  42. ++first;
  43. }
  44. if(value) return value.get();
  45. boost::throw_exception(no_slots_error());
  46. }
  47. };
  48. template<>
  49. class last_value<void> {
  50. public:
  51. typedef void result_type;
  52. template<typename InputIterator>
  53. result_type operator()(InputIterator first, InputIterator last) const
  54. {
  55. while (first != last)
  56. {
  57. try
  58. {
  59. *first;
  60. }
  61. catch(const expired_slot &) {}
  62. ++first;
  63. }
  64. return;
  65. }
  66. };
  67. } // namespace signals2
  68. } // namespace boost
  69. #endif // BOOST_SIGNALS2_LAST_VALUE_HPP