Note: This tutorial assumes that you have completed the previous tutorials: Writing a Simple Publisher and Subscriber, Writing a Simple Service.

Using Class Methods as Callbacks

Description: Most of the tutorials use functions in their examples, rather than class methods. This is because using functions is simpler, not because class methods are unsupported. This tutorial will show you how to use class methods for subscription and service callbacks.

Tutorial Level: BEGINNER

Subscriptions

Suppose you have a simple class, Listener:

  35 class Listener
  36 {
  37 public:
  38   void callback(const std_msgs::String::ConstPtr& msg);
  39 };

Where the NodeHandle::subscribe() call using a function would have looked like this:

  78   ros::Subscriber sub = n.subscribe("chatter", 1000, chatterCallback);

Using a class method looks like this:

  53   Listener listener;
  54   ros::Subscriber sub = n.subscribe("chatter", 1000, &Listener::callback, &listener);

Service Servers

Suppose you have a simple class, AddTwo:

  31 class AddTwo
  32 {
  33 public:
  34   bool add(roscpp_tutorials::TwoInts::Request& req,
  35            roscpp_tutorials::TwoInts::Response& res);
  36 };

Where the old NodeHandle::advertiseService() call would look like:

  45   ros::ServiceServer service = n.advertiseService("add_two_ints", add);

The class version looks like this:

  54   AddTwo a;
  55   ros::ServiceServer ss = n.advertiseService("add_two_ints", &AddTwo::add, &a);

For the full set of subscribe(), advertiseService(), etc. overloads, see the NodeHandle class documentation

Wiki: roscpp_tutorials/Tutorials/UsingClassMethodsAsCallbacks (last edited 2010-07-30 22:06:20 by JoshFaust)