Ask Your Question
0

Why to use std::bind to declare the callback function

asked 2021-03-16 17:16:55 -0500

pablo.arandarod gravatar image

I'm learning about ROS2, and I was creating my own project, and I cannot understand why, when the callback function is declared in the wall timer, this one has to be declared with std::bind.

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted
2

answered 2021-03-24 14:53:52 -0500

CroCo gravatar image

This has to do with C++. Usually, when you create a class, you want to encapsulate your data inside the class. Callback functions are a problem and tricky when they are created as member data of a class. There is a plethora of libraries that are written in C that have callback functions through which one can access , for example, to mouse movement or keyboard. SDL2, Freeglue, SFML,..., etc, are such examples. Callback functions are extremely common in C programming, however, in C, there is no concept for OOP. C++ tries to be fully compatible with C codes. One of many solutions in C++ that allow developers to treat callback functions as member data is to use std::bind(). You can search for this since it is common issue when you deal with C libraries.

edit flag offensive delete link more
2

answered 2021-03-24 12:23:19 -0500

clyde gravatar image

You don't. A lambda example:

timer_ = create_wall_timer(
   std::chrono::milliseconds(100),
   []{ std::cout << "Hello, world" << std::endl; }
);
edit flag offensive delete link more

Comments

"You don't" implies that it's bad to use std::bind. There are a couple of packages I have seen that regulary use std::bind. So Your example is a great way of showing how it is solved without a std::bind, but using std::bind is also still valid! :)

flo gravatar image flo  ( 2021-09-23 15:28:52 -0500 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

2 followers

Stats

Asked: 2021-03-16 17:16:55 -0500

Seen: 117 times

Last updated: Mar 24