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 class Context
34 {
35 public:
37 
39  Context();
40 
41  template<typename SubContext, typename ... Args>
43  get_sub_context(Args && ... args)
44  {
45  std::lock_guard<std::mutex> lock(mutex_);
46 
47  std::type_index type_i(typeid(SubContext));
48  std::shared_ptr<SubContext> sub_context;
49  auto it = sub_contexts_.find(type_i);
50  if (it == sub_contexts_.end()) {
51  // It doesn't exist yet, make it
52  sub_context = std::shared_ptr<SubContext>(
53  new SubContext(std::forward<Args>(args) ...),
54  [](SubContext * sub_context_ptr) {
55  delete sub_context_ptr;
56  });
57  sub_contexts_[type_i] = sub_context;
58  } else {
59  // It exists, get it out and cast it.
60  sub_context = std::static_pointer_cast<SubContext>(it->second);
61  }
62  return sub_context;
63  }
64 
65 private:
67 
69  std::mutex mutex_;
70 };
71 
72 } // namespace rclcpp
73 
74 #endif // RCLCPP__CONTEXT_HPP_
#define RCLCPP_DISABLE_COPY(...)
Definition: macros.hpp:26
std::shared_ptr< SubContext > get_sub_context(Args &&... args)
Definition: context.hpp:43
Definition: allocator_common.hpp:24
T end(T... args)
Definition: context.hpp:33
#define RCLCPP_SMART_PTR_DEFINITIONS(...)
Definition: macros.hpp:36
T static_pointer_cast(T... args)
T find(T... args)
#define RCLCPP_PUBLIC
Definition: visibility_control.hpp:50