Telnet++
A C++ library for interacting with Telnet streams
router.hpp
1 #pragma once
2 
3 #include "telnetpp/detail/return_default.hpp"
4 #include <functional>
5 #include <map>
6 #include <type_traits>
7 #include <utility>
8 
9 namespace telnetpp { namespace detail {
10 
11 //* =========================================================================
47 //* =========================================================================
48 template <
49  class Key
50  , class Message
51  , class Result
52  , class KeyFromMessagePolicy
53 >
54 class router
55 {
56 public :
57  typedef Key key_type;
58  typedef Message message_type;
59  typedef Result result_type;
60  typedef std::function<Result (Message const&)> function_type;
61  typedef std::map
62  <
63  key_type
64  , function_type
65  > registered_functions_map_type;
66 
67  //* =====================================================================
72  //* =====================================================================
73  template <typename KeyType, typename Function>
74  void register_route(
75  KeyType &&key,
76  Function &&function)
77  {
78  registered_functions_[std::forward<KeyType>(key)] =
79  std::forward<Function>(function);
80  }
81 
82  //* =====================================================================
87  //* =====================================================================
88  template <typename KeyType>
89  void unregister_route(KeyType &&key)
90  {
91  registered_functions_.erase(std::forward<KeyType>(key));
92  }
93 
94  //* =====================================================================
99  //* =====================================================================
100  template <typename Function>
101  void set_unregistered_route(Function &&route)
102  {
103  unregistered_route_ = std::forward<Function>(route);
104  }
105 
106  //* =====================================================================
113  //* =====================================================================
114  Result operator()(Message const& message) const
115  {
116  auto iter = registered_functions_.find(
117  KeyFromMessagePolicy::key_from_message(message));
118 
119  if (iter != registered_functions_.end())
120  {
121  return iter->second(message);
122  }
123  else if (unregistered_route_ != nullptr)
124  {
125  return unregistered_route_(message);
126  }
127 
128  // This garbage is just to return either a default-constructed Result,
129  // or void if Result is void.
130  return detail::return_default_constructed<Result>{}();
131  }
132 
133 private :
134  registered_functions_map_type registered_functions_;
135  function_type unregistered_route_;
136 };
137 
138 }}
Definition: byte_converter.hpp:4