rclcpp  master
C++ ROS Client Library API
context.hpp
Go to the documentation of this file.
1 // Copyright 2014 Open Source Robotics Foundation, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #ifndef RCLCPP__CONTEXT_HPP_
16 #define RCLCPP__CONTEXT_HPP_
17 
18 #include <iostream>
19 #include <memory>
20 #include <mutex>
21 #include <typeindex>
22 #include <typeinfo>
23 #include <unordered_map>
24 #include <utility>
25 
26 #include "rclcpp/macros.hpp"
28 #include "rmw/rmw.h"
29 
30 namespace rclcpp
31 {
32 
33 namespace context
34 {
35 
36 class Context
37 {
38 public:
40 
42  Context();
43 
44  template<typename SubContext, typename ... Args>
45  std::shared_ptr<SubContext>
46  get_sub_context(Args && ... args)
47  {
48  std::lock_guard<std::mutex> lock(mutex_);
49 
50  std::type_index type_i(typeid(SubContext));
51  std::shared_ptr<SubContext> sub_context;
52  auto it = sub_contexts_.find(type_i);
53  if (it == sub_contexts_.end()) {
54  // It doesn't exist yet, make it
55  // *INDENT-OFF* (prevent uncrustify from making unnecessary indents here)
56  sub_context = std::shared_ptr<SubContext>(
57  new SubContext(std::forward<Args>(args) ...),
58  [] (SubContext * sub_context_ptr) {
59  delete sub_context_ptr;
60  });
61  // *INDENT-ON*
62  sub_contexts_[type_i] = sub_context;
63  } else {
64  // It exists, get it out and cast it.
65  sub_context = std::static_pointer_cast<SubContext>(it->second);
66  }
67  return sub_context;
68  }
69 
70 private:
71  RCLCPP_DISABLE_COPY(Context)
72 
73  std::unordered_map<std::type_index, std::shared_ptr<void>> sub_contexts_;
74  std::mutex mutex_;
75 };
76 
77 } // namespace context
78 } // namespace rclcpp
79 
80 #endif // RCLCPP__CONTEXT_HPP_
#define RCLCPP_DISABLE_COPY(...)
Definition: macros.hpp:26
Definition: allocator_common.hpp:24
Definition: context.hpp:36
#define RCLCPP_SMART_PTR_DEFINITIONS(...)
Definition: macros.hpp:36
std::shared_ptr< SubContext > get_sub_context(Args &&... args)
Definition: context.hpp:46
#define RCLCPP_PUBLIC
Definition: visibility_control.hpp:50