diff --git a/rclcpp/include/rclcpp/node.hpp b/rclcpp/include/rclcpp/node.hpp index 7e5f402f8a..2150f60e1c 100644 --- a/rclcpp/include/rclcpp/node.hpp +++ b/rclcpp/include/rclcpp/node.hpp @@ -720,6 +720,24 @@ class Node : public std::enable_shared_from_this ParameterT & parameter, const ParameterT & alternative_value) const; + /// Return the parameter value, or the "alternative_value" if not set. + /** + * If the parameter was not set, then the "alternative_value" argument is returned. + * + * This method will not throw the rclcpp::exceptions::ParameterNotDeclaredException exception. + * + * In all cases, the parameter is never set or declared within the node. + * + * \param[in] name The name of the parameter to get. + * \param[in] alternative_value Value to be stored in output if the parameter was not set. + * \returns The value of the parameter. + */ + template + ParameterT + get_parameter_or( + const std::string & name, + const ParameterT & alternative_value) const; + /// Return the parameters by the given parameter names. /** * Like get_parameters(), this method may throw the diff --git a/rclcpp/include/rclcpp/node_impl.hpp b/rclcpp/include/rclcpp/node_impl.hpp index 46f54aa054..086c2bb17c 100644 --- a/rclcpp/include/rclcpp/node_impl.hpp +++ b/rclcpp/include/rclcpp/node_impl.hpp @@ -313,6 +313,17 @@ Node::get_parameter_or( return got_parameter; } +template +ParameterT +Node::get_parameter_or( + const std::string & name, + const ParameterT & alternative_value) const +{ + ParameterT parameter; + get_parameter_or(name, parameter, alternative_value); + return parameter; +} + // this is a partially-specialized version of get_parameter above, // where our concrete type for ParameterT is std::map, but the to-be-determined // type is the value in the map. diff --git a/rclcpp/test/rclcpp/test_node.cpp b/rclcpp/test/rclcpp/test_node.cpp index f3fb13119f..7b4bade94b 100644 --- a/rclcpp/test/rclcpp/test_node.cpp +++ b/rclcpp/test/rclcpp/test_node.cpp @@ -2075,6 +2075,33 @@ TEST_F(TestNode, get_parameter_or_undeclared_parameters_allowed) { } } +// test get_parameter_or with return value +TEST_F(TestNode, get_parameter_or_with_return_value) { + auto node = std::make_shared( + "test_get_parameter_or_node"_unq); + { + // normal use (declare first) still works + auto name = "parameter"_unq; + + node->declare_parameter(name, 42); + EXPECT_TRUE(node->has_parameter(name)); + + { + const int value = node->get_parameter_or(name, 43); + EXPECT_EQ(value, 42); + } + } + { + // normal use, no declare first + auto name = "parameter"_unq; + + { + const int value = node->get_parameter_or(name, 43); + EXPECT_EQ(value, 43); + } + } +} + // test get_parameters with undeclared not allowed TEST_F(TestNode, get_parameters_undeclared_parameters_not_allowed) { auto node = std::make_shared(