3

I'm currently learning new features in C++11 and boost, such as lambda and boost::function.
I'm trying to use boost.lambda in std::for_each, with the iterated type being boost::function.
The code looks like this:

void task1(int a)
{
  std::cout << "task1: " << a << std::endl;
}

void task2(const std::string& str)
{
  std::cout << "task2: " << str << std::endl;
}

int main()
{
  std::list<boost::function<void()> > functions;
  functions.push_back(boost::bind(&task1, 5));
  functions.push_back(boost::bind(&task2, "test string"));

  // working
  std::list<boost::function<void()> >::iterator i = functions.begin();
  for (; i != functions.end(); ++i)
  {
    (*i)();
  }
  // also working
  std::for_each(functions.begin(), functions.end(), [](boost::function<void()>& f){f();});

  // trying to use boost::lambda but none compiles.
  std::for_each(functions.begin(), functions.end(), boost::lambda::bind(_1));

  std::for_each(
      functions.begin(),
      functions.end(),
      boost::lambda::bind(&boost::function<void()>::operator(), &_1, _1));

  std::for_each(
      functions.begin(),
      functions.end(),
      boost::lambda::bind(std::mem_fn(&boost::function<void()>::operator(), _1));

  return 0;
}

How can call a boost::function object with boost::lambda? I think I'm supposed to wrap it with boost::lambda::bind(), but I just don't know how. I have read the boost.lambda document, but I didn't find anything useful there.

3
  • 7
    If you have C++11, why use boost::function, boost::bind and boost::lambda instead of the standard std::function, std::bind and native lambdas? Commented Feb 28, 2014 at 10:53
  • 2
    Correct me if I'm wrong, but I think ADL is coming into play here. For some reason, if you don't explicitly qualify boost::lambda::_1, it will use boost/bind/arg.hpp instead. Remove boost/bind.hpp to see what I mean. Commented Feb 28, 2014 at 11:37
  • @JoachimPileborg: I know C++11's native lambda is much more powerful than boost's, but on I don't always have C++11 support on some dev platforms. Also, sometimes boost::lambda is easier to use than native lambda. I was just trying out boost and native lambda. Commented Mar 1, 2014 at 2:15

1 Answer 1

2

In order for this to work, you must explicitly qualify boost::lambda so that you mean boost::lambda::_1 and not boost::arg from boost/bind.

  std::for_each(functions.begin(), functions.end(), 
        boost::lambda::bind(boost::lambda::_1));
Sign up to request clarification or add additional context in comments.

1 Comment

That's correct! I used boost.lambda.bind instead of boost.bind, but I forgot _1.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.