0
$\begingroup$

I would like to use the same callback for subscriptions to different topics with different types. I have searched on the internet and could not a wokring approach. My idea was to templetize the callback. Something going like this:

template <typename T>
void update_vehicle_callback(const std::shared_ptr<T> msg, const std::string &topic)

This callback would be associated by different subscribers of different topics and different types.

For the sake of clarity let me do an example:

I have topic "cmd_vel" of type Twist and topic "pose" of type PoseStamped. I want to bind to both subscriber the same update_vehicle_callback without defining 2 different callbacks that calls the same method:

void cmd_vel_cb(msg){
   update_vehicle_info(msg);
}
void pose_cb(msg){
   update_vehicle_info(msg);
}

This is because in reality I have a lot of different topics.

Is there a way to achieve this?

$\endgroup$

1 Answer 1

1
$\begingroup$

For those passing by for a solution here it is: Define a template callback:

template <typename T>
    void update_info(const std::shared_ptr<T> msg);

And each subscriber in the following way:

    odom_subscriber = this->create_subscription<nav_msgs::msg::Odometry>("odom", qos_besteffort_keep_1_volatile, std::bind(&ClassName::update_info<nav_msgs::msg::Odometry>, this, std::placeholders::_1));
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.