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 <clalancette@openrobotics.org>

* Review fixes (one sentence per line).

Signed-off-by: Chris Lalancette <clalancette@openrobotics.org>

* Rename get_parameter_or_set_default -> get_parameter_or_set

Signed-off-by: Chris Lalancette <clalancette@openrobotics.org>
This commit is contained in:
Chris Lalancette 2018-09-20 09:21:24 -04:00 committed by GitHub
parent b860b899e5
commit be8c05ed9e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 34 additions and 0 deletions

View file

@ -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<typename ParameterT>
void
get_parameter_or_set(
const std::string & name,
ParameterT & value,
const ParameterT & alternative_value);
RCLCPP_PUBLIC
std::vector<rcl_interfaces::msg::ParameterDescriptor>
describe_parameters(const std::vector<std::string> & names) const;

View file

@ -250,6 +250,22 @@ Node::get_parameter_or(
return got_parameter;
}
template<typename ParameterT>
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_