ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question
3

How can I subscribe to a topic, using a parent class function as the callback?

asked 2014-08-21 21:26:21 -0500

falseazure gravatar image

I have a subscriber that is currently set up with a class method that is called when a message is received from a topic. The code is pretty standard:

ros::Subscriber StageOdo_sub = n.subscribe<nav_msgs::Odometry>("robot_0/odom",1000, &MyClass::StageOdom_callback,this);

I need to shift the callback function to a superclass / base class. However, this generates errors and notes that say that template argument substitution failed. How can I ensure that the superclass function is called?

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
3

answered 2014-08-22 01:05:52 -0500

Wolf gravatar image

updated 2014-08-22 02:46:29 -0500

I assume this is e. g. of type MyDerivedClass* where MyDerivedClass inherits from MyClass and the method StageOdom_callback of class MyClass is protected or public (not private!).

If so have you tried:

ros::Subscriber StageOdo_sub = n.subscribe("robot_0/odom",1000, &MyClass::StageOdom_callback, dynamic_cast<MyClass*>( this ) );

If your compiler does not provide dynamic_cast you could also use reinterpret_cast<MyClass*>. However, dynamic_cast is safer as it checks at runtime that the class of the object pointed to by this really inherits from MyClass...

Edit:

I just noticed: you do not need to explizitly select the template type (<nav_msgs::Odometry>) like you do with advertise. The Template type is implizitly selected from the callback argument type...

edit flag offensive delete link more

Comments

Great answer, thank you! I appreciate the heads up about selecting the template type, too.

falseazure gravatar image falseazure  ( 2014-08-23 00:18:07 -0500 )edit

Hello! I realize this is a pretty old topic but this was incredibly helpful to me when trying to create a timer using a parent callback. I was curious why you have to cast this. Can anyone shed some light on that?

wdudzik gravatar image wdudzik  ( 2019-12-05 13:01:13 -0500 )edit

Question Tools

1 follower

Stats

Asked: 2014-08-21 21:26:21 -0500

Seen: 1,107 times

Last updated: Aug 22 '14