jeudi 29 octobre 2020

ROS 2 Subscriber Callback with a method of member class

I'd like to use member class method in callback function. The following C++ code is a simple subscriber with a callback using a member class method hello().

#include <functional>
#include <memory>

#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"

using std::placeholders::_1;

class Subclass
{
private:
public:
    Subclass(/* args */);
    ~Subclass();
    std::string hello(std::string &s)
    {
        return "Hello " + s;
    }
};

class MinimalSubscriber : public rclcpp::Node
{
public:
    MinimalSubscriber()
        : Node("minimal_subscriber")
    {
        subscription_ = this->create_subscription<std_msgs::msg::String>(
            "topic", 10, std::bind(&MinimalSubscriber::topic_callback, this, _1));
    }

private:
    Subclass subclass_;
    void topic_callback(const std_msgs::msg::String::SharedPtr msg) const
    {
        std::string s = subclass_.hello(msg->data);
        RCLCPP_INFO(this->get_logger(), "I heard: '%s'", s.c_str());
    }
    rclcpp::Subscription<std_msgs::msg::String>::SharedPtr subscription_;
};

int main(int argc, char *argv[])
{
    rclcpp::init(argc, argv);
    rclcpp::spin(std::make_shared<MinimalSubscriber>());
    rclcpp::shutdown();
    return 0;
}

I build the C++ code and I catch below message. How I fix the code? ROS2 Foxy in Ubuntu LTS 20.04 is used to build.

/home/ubuntu/dev_ws/src/ros2_pigpio/src/subclass.cpp: In member function ‘void MinimalSubscriber::topic_callback(std_msgs::msg::String_<std::allocator<void> >::SharedPtr) const’:
/home/ubuntu/dev_ws/src/ros2_pigpio/src/subclass.cpp:35:50: error: passing ‘const Subclass’ as ‘this’ argument discards qualifiers [-fpermissive]
   35 |         std::string s = subclass_.hello(msg->data);
      |                                                  ^
/home/ubuntu/dev_ws/src/ros2_pigpio/src/subclass.cpp:15:17: note:   in call to std::string Subclass::hello(std::string&)’
   15 |     std::string hello(std::string &s)
      |                 ^~~~~
make[2]: *** [CMakeFiles/subclass.dir/build.make:63: CMakeFiles/subclass.dir/src/subclass.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:84: CMakeFiles/subclass.dir/all] Error 2
make: *** [Makefile:141: all] Error 2

Aucun commentaire:

Enregistrer un commentaire