【发布时间】:2021-10-16 23:05:22
【问题描述】:
我对 C++ 相当陌生,我对 std::bind 的做法有疑问。下面的 sn-p 就是从这个tutorial on the ROS2 website 复制过来的。该代码创建了一个类,其中 timer_ 字段承载了一个使用create_wall_timer() 创建的计时器。 creates_wall_timer() 接受 CallbackT && 类型的回调对象。在类的构造函数中,为什么作者将std::bind(...)的结果作为回调传递给create_timer(),而不是直接指针或引用timer_callback方法?
对冗长的问题表示歉意。我不太擅长问这些问题。希望我没有错过您需要的太多信息。
#include <chrono>
#include <functional>
#include <memory>
#include <string>
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using namespace std::chrono_literals;
/* This example creates a subclass of Node and uses std::bind() to register a
* member function as a callback from the timer. */
class MinimalPublisher : public rclcpp::Node
{
public:
MinimalPublisher()
: Node("minimal_publisher"), count_(0)
{
publisher_ = this->create_publisher<std_msgs::msg::String>("topic", 10);
timer_ = this->create_wall_timer(
500ms, std::bind(&MinimalPublisher::timer_callback, this));
}
private:
void timer_callback()
{
auto message = std_msgs::msg::String();
message.data = "Hello, world! " + std::to_string(count_++);
RCLCPP_INFO(this->get_logger(), "Publishing: '%s'", message.data.c_str());
publisher_->publish(message);
}
rclcpp::TimerBase::SharedPtr timer_;
rclcpp::Publisher<std_msgs::msg::String>::SharedPtr publisher_;
size_t count_;
};
【问题讨论】:
-
我们需要
create_wall_timer的声明。但很可能create_wall_timer接受一个没有参数的函数对象,而一个成员方法有一个隐藏的this参数,这就是使用bind 的原因。