From be8c05ed9e5e0a2e58d90855a5ca166462464ba9 Mon Sep 17 00:00:00 2001 From: Chris Lalancette Date: Thu, 20 Sep 2018 09:21:24 -0400 Subject: [PATCH] Implement get_parameter_or_set_default. (#551) * Implement get_parameter_or_set_default. This is syntactic sugar to allow the user to get a parameter. If the parameter is already set on the node, it gets the value of the parameter. If it is not set, then it gets the alternative value and sets it on the node, ensuring that it exists. Signed-off-by: Chris Lalancette * Review fixes (one sentence per line). Signed-off-by: Chris Lalancette * Rename get_parameter_or_set_default -> get_parameter_or_set Signed-off-by: Chris Lalancette --- rclcpp/include/rclcpp/node.hpp | 18 ++++++++++++++++++ rclcpp/include/rclcpp/node_impl.hpp | 16 ++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/rclcpp/include/rclcpp/node.hpp b/rclcpp/include/rclcpp/node.hpp index 035c49c..d2a996d 100644 --- a/rclcpp/include/rclcpp/node.hpp +++ b/rclcpp/include/rclcpp/node.hpp @@ -321,6 +321,24 @@ public: ParameterT & value, const ParameterT & alternative_value) const; + /// Get the parameter value; if not set, set the "alternative value" and store it in the node. + /** + * If the parameter is set, then the "value" argument is assigned the value + * in the parameter. + * If the parameter is not set, then the "value" argument is assigned the "alternative_value", + * and the parameter is set to the "alternative_value" on the node. + * + * \param[in] name The name of the parameter to get. + * \param[out] value The output where the value of the parameter should be assigned. + * \param[in] alternative_value Value to be stored in output and parameter if the parameter was not set. + */ + template + void + get_parameter_or_set( + const std::string & name, + ParameterT & value, + const ParameterT & alternative_value); + RCLCPP_PUBLIC std::vector describe_parameters(const std::vector & names) const; diff --git a/rclcpp/include/rclcpp/node_impl.hpp b/rclcpp/include/rclcpp/node_impl.hpp index 716266f..c664b55 100644 --- a/rclcpp/include/rclcpp/node_impl.hpp +++ b/rclcpp/include/rclcpp/node_impl.hpp @@ -250,6 +250,22 @@ Node::get_parameter_or( return got_parameter; } +template +void +Node::get_parameter_or_set( + const std::string & name, + ParameterT & value, + const ParameterT & alternative_value) +{ + bool got_parameter = get_parameter(name, value); + if (!got_parameter) { + this->set_parameters({ + rclcpp::Parameter(name, alternative_value), + }); + value = alternative_value; + } +} + } // namespace rclcpp #endif // RCLCPP__NODE_IMPL_HPP_