From 5568cc2326c94eb2af7c6d130f0652bba3ec3fa5 Mon Sep 17 00:00:00 2001 From: William Woodall Date: Tue, 18 Aug 2015 18:43:05 -0700 Subject: [PATCH] allow storing arbitrary singletons in the Context --- rclcpp/include/rclcpp/context.hpp | 41 ++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/rclcpp/include/rclcpp/context.hpp b/rclcpp/include/rclcpp/context.hpp index 5528792..f859a7f 100644 --- a/rclcpp/include/rclcpp/context.hpp +++ b/rclcpp/include/rclcpp/context.hpp @@ -15,16 +15,24 @@ #ifndef RCLCPP_RCLCPP_CONTEXT_HPP_ #define RCLCPP_RCLCPP_CONTEXT_HPP_ -#include - #include +#include + +#include +#include +#include +#include +#include + +#include + namespace rclcpp { + namespace context { -/* ROS Context */ class Context { public: @@ -32,9 +40,36 @@ public: Context() {} + template + std::shared_ptr + get_sub_context(Args && ... args) + { + std::lock_guard lock(mutex_); + + std::type_index type_i(typeid(SubContext)); + std::shared_ptr sub_context; + auto it = sub_contexts_.find(type_i); + if (it == sub_contexts_.end()) { + // It doesn't exist yet, make it + sub_context = std::shared_ptr( + new SubContext(std::forward(args) ...), + [] (SubContext * sub_context_ptr) { + delete sub_context_ptr; + }); + sub_contexts_[type_i] = sub_context; + } else { + // It exists, get it out and cast it. + sub_context = std::static_pointer_cast(it->second); + } + return sub_context; + } + private: RCLCPP_DISABLE_COPY(Context); + std::unordered_map> sub_contexts_; + std::mutex mutex_; + }; } /* namespace context */