ROS generic subscriber as a class method
Here I am trying this example's subscriber example code from facontidavide and it works fine as it is. However when I put the topicCallback()
in a Class, it's instances appear to share its global variables - whether they are public or private.
class Foo{
private:
std::string _topic;
public:
Foo(std::map <std::string, std::string>& info)
{
_topic = info["topic"];
};
void topicCallback(const topic_tools::ShapeShifter::ConstPtr& msg,
const std::string &topic_name,
RosIntrospection::Parser& parser)
{
---EXAMPLE CODE---
cout << _topic << endl;
}
}
main(){
---SOME CODE---
for (auto &info : topics)
{
Foo f(info);
boost::function<void(const topic_tools::ShapeShifter::ConstPtr&) > callback;
callback = [&parser, &info, &f](const topic_tools::ShapeShifter::ConstPtr& msg)->void
{
f.topicCallback(msg, info.at("topic"), parser) ;
};
subscribers.push_back( nh.subscribe(info["topic"], 10, callback) );
}
---SOME MORE CODE---
}
When I create several instances of the class and subscribe to the callback just as in the example code, _topic
appears to be the same for all instances. Actually it is the topic of the last instance I create.
This probably might be due to my little understanding of C++11. It'd be a great help if someone could point out what I am doing wrong here.
Edit: Yes it is a C++ related question. But I don't think I'll get an answer by asking this on stackoverflow. I tried using boost::bind
instead using a lambda. But it gives some unrecognizable errors like error: use of deleted function xxx
May be due to the callback expecting a topic_tools::ShapeShifter
for all message types?
I have a feeling this has more to with your use of the lambda there and how you are capturing the context than with anything ROS related.