#include "ros/ros.h"
#include "std_msgs/String.h"
/**
* This tutorial demonstrates a simple use of Boost.Bind to pass arbitrary data into a subscription
* callback. For more information on Boost.Bind see the documentation on the boost homepage,
* http://www.boost.org/
*/
class Listener
{
public:
ros::NodeHandle node_handle_;
ros::V_Subscriber subs_; //std::vector<Subscriber> 向量容器
Listener(const ros::NodeHandle& node_handle)
: node_handle_(node_handle) //冒号的含义是使用参数node_handle对类的成员node_handle_进行初始化
{
}
void init() //Listener类的init()方法
{
// std::vector<Subscriber>.push_back()在容器尾部加入一个Subscriber对象(节点句柄的subscribe方法返回的) ,
// boost::bind方法将一个函数转化成另一个函数
subs_.push_back(node_handle_.subscribe<std_msgs::String>("chatter", 1000, boost::bind(&Listener::chatterCallback, this, _1, "User 1")));
subs_.push_back(node_handle_.subscribe<std_msgs::String>("chatter", 1000, boost::bind(&Listener::chatterCallback, this, _1, "User 2")));
subs_.push_back(node_handle_.subscribe<std_msgs::String>("chatter", 1000, boost::bind(&Listener::chatterCallback, this, _1, "User 3")));
}
void chatterCallback(const std_msgs::String::ConstPtr& msg, std::string user_string) //被boost::bind()转化之前的消息回调函数
{
ROS_INFO("I heard: [%s] with user string [%s]", msg->data.c_str(), user_string.c_str());
}
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "listener_with_userdata");
ros::NodeHandle n; //创建节点句柄
Listener l(n); //创建Listener类
l.init(); //调用Listener类的init()方法,创建3个话题订阅者,并压入容器
ros::spin(); //调用spin()方法,统一调用消息回调函数
return 0;
}
boost::bind()将第一个参数(函数对象)转化为另一个函数对象,转化之前的函数参数由_x占位符代替
这里,在消息处理时,消息被传入boost::bind(),它将该消息传入chatterCallback()函数的第一个参数,第二个参数使用“User 1”等。
参考链接: http://blog.csdn.net/hopingwhite/article/details/6278472