#include
#include
#include
#include
#include
#include "sys/time.h"
#include "rclcpp/rclcpp.hpp"
#include "std_msgs/msg/string.hpp"
using namespace std;
using namespace rclcpp;
//C++
class mynode:rclcpp::Node
{
public:
mynode(string str):Node(str) //constructor
{
timer_=this->create_wall_timer(500ms,[this]()->void {return this->mynode::timer_callback(); });
}
private:
uint32_t count1=0;
stringstream ss;
std_msgs::msg::String MESSAGE1;
rclcpp::TimerBase::SharedPtr timer_;
rclcpp::Node * pnode;
std::shared_ptr> ppublisher=0;
void timer_callback()
{
ss.str("");
ss<<"hello nice to meet you"<create_publisher("topicName",10);
ppublisher->publish(MESSAGE1);
//destroy the pointer
}
};
int main(int argc,char ** argv)
{
rclcpp::init(argc,argv);
rclcpp::shutdown();
return 0;
}
这个里面没有使用bind函数作为返回参数,而使用了lambda函数作为了返回参数也就是回调函数。后面可能也会用一用这个bind函数,还有啊我要说一下有2个老师这个词语都没有读对,这个函数多做baind,麻烦去查一下词典,聋哑英语害死人
lambda表达式在这个里面的语句是:
timer_=this->create_wall_timer(500ms,[this]()->void {return this->mynode::timer_callback(); });出现在这个语句里面;
而lambda表达式就是这部分
[this]()->void {return this->mynode::timer_callback(); }
这是一个整体表达式叫做lambda表达式。首先这个个东西的本质是一个没有名字的函数---无名函数。他的返回值是有函数体里面return决定的,这里return this->mynode::timer_callback(),那么返回值就是这个东西这应该就是返回了一个函数了。
为什么要使用这个东西呢?我们的目标就是要把定时器到了时间点的时候,把处理的函数放在这个位置,如果是普通的函数就直接用函数名可以了,但是timer_callback()是一个类的成员函数,
如果直接将放进去,就会出现一个疑问:是那个对象调用的这个函数?所以需要指明是this.就是我们自己的这个对象调用的。实现这个功能可以使用lambda表达式,所以就是这么回事:
【】中括号里面写个this是表示我要使用this这个参数,并且是值传递,不是引用传递,如果引用传递使用¶m_name这样的款式,[¶m_name](int a,int b)->void { ;}