Rob Walker
Rob Walker

Reputation: 47452

How to use std::for_each on a member function

I am trying to pick up the more 'functional' style of STL programming, and have the following simplified case

class Widget;

class Zot
{
public:
  std::vector<Widget> Widgets;

  void ProcessAWidget(int x, Widget w) { ... }

  void Process()
  {
      int ctx=123;

      std::for_each(Widgets.begin(), Widgets.end(), 
           std::bind(&Zot::ProcessAWidget, this, ctx, _1));
   }
};

Is there a better way of writing the last parameter for the for_each call?

In particular having to explicitly mention this feels 'wrong', and dropping the class qualifier would be good too.

Upvotes: 3

Views: 1387

Answers (4)

user10609288
user10609288

Reputation:

Your solution:

until c++11

    std::for_each( container.cbegin(), container.cend(), std::bind1st(std::mem_fun(&MyClass::method), this) );

after:

    std::for_each( container.cbegin(), container.cend(),std::bind(&MyClass::method, this,  std::placeholders::_1));

Upvotes: 0

Kerrek SB
Kerrek SB

Reputation: 476970

Lambdas to the rescue:

std::for_each(Widgets.begin(), Widgets.end(),
              [=](Widget & w) { ProcessAWidget(ctx, w); });

Upvotes: 7

hmjd
hmjd

Reputation: 121961

If the compiler supports C++11 lambdas:

std::for_each(Widgets.begin(),
              Widgets.end(),
              [&](Widget& a_w) { ProcessAWidget(ctx, a_w); });

Upvotes: 8

Adrian McCarthy
Adrian McCarthy

Reputation: 47954

In C++11, you can use a lambda function with std::for_each, which often makes the code much more readable than the games you have to play with std::bind.

Upvotes: 2

Related Questions