Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use bind instead of function call?

What is the advantage of using boost::bind in this case

std::for_each(participants_.begin(), participants_.end(),
    boost::bind(&chat_participant::deliver, _1, boost::ref(msg)));

instead of

for(iterator actual = participants_.begin(); actual != participants_.end(); ++actual)
    (*actual)->deliver(msg);



Link to the whole code (this is a simple server example provided by boost tutorials).

like image 490
Łukasz Kosiak Avatar asked Mar 23 '14 15:03

Łukasz Kosiak


2 Answers

I think it's simply that pre C++11, algorithms were generally recommended over plain for-loops for most things. In theory, it's easier to understand the purpose of the code, as you don't have to understand the whole loop implementation first. for_each is perhaps an extreme though, since its for-loop implementation would be the simplest.

Before lambda functions, 'boost::bind' was simply a requirement if you wanted to use the algorithm without defining a custom functor.

Nowadays, with range-based for loops, you'd just do this:

for (auto& participant : participants)
    participant->deliver(msg);

Algorithms are still better for more complicated loops though (especially now you don't have to use 'boost::bind').

like image 149
user673679 Avatar answered Oct 09 '22 09:10

user673679


Both of them do the same job. boost::bind creates a function object, which works mostly like a function pointer in C. So the question maybe why they do that it the C++ way.
C++ is an Object-Oriented language, it comes with the standard library(STL), which provides several data structures(called class) such as container(list, set, map, iterator concept...etc) and others utilities. It also provides algorithms that work on that class(find, sort, filter..etc). So, for algorithms to work with these container in an uniform way, the container must follow some rules.
std::for_each is a part of STL algorithms, so that's the way it works.
But why the C++ way looks good?

  1. Just as @user673679 said, we don't lose focus on implement the loop anymore.
  2. Traditionally loops create inner blocks, several inner blocks sometimes make it difficult to follow the logic.
  3. You can reuse the functions' work on single element.
like image 32
secmask Avatar answered Oct 09 '22 10:10

secmask