开发者

lambda expression conversion

I am trying to convert a function written using new standard(C++ 0x) back to previous standard

How can I convert the following line

typedef std::vector<value3 const*> passmem;
pasmem pm; // neighborhood sequence
 std::for_each(pm.begin(), pm.end(), [&]开发者_运维技巧 (value3 const* x)


Just convert the lambda expression into a named function and pass it as a parameter to for_each. Alternatively just do the function of your lambda function inline like:

   for (pasmem::iterator it=pm.begin(); it != pm.end(); ++it) {
      // Do the lambda functionality with *it
   }


for(passmem::const_iterator i = pm.begin(); i != pm.end(); ++i)
{
   const value3* x = *i;
   // same as in lambda
}


The basic rules for processing a lambda require creating a function object that offers operator() with the same signature as the lambda. For each one of the captured fields, you will need to add a member to the functor and initialize it in construction. In your particular case that would be by reference or const reference, depending on where your lambda is being defined and the types involved.

If, for a non-trivial, the lambda was accumulating the value of each element in the vector into a local variable, and (assuming that value3 has the appropriate operators):

struct accumulator__ {
    value3 & v_;
    accumulator__( value3 & v ) : v_(v) {}

    void                                   // for_each ignores the return value
    operator()( value3 const * p ) {       // same argument as lambda
       v_ += *p;
    }
};

If the lambda was defined as a member function, and it accessed any member of the class, then things would become a little trickier, but you would basically have to create the closure of all accessed fields manually (i.e. adding [const] references of all the accessed members. Real lambdas (I believe) only capture this but in the refactoring you may loose access rights to the members of the class.


At first, @george272 has the solution (although I'd call iterator (c)it and not i).

Going back to your original code, you should not (almost) ever use for_each in C++11.

Here is why:

typedef std::vector<value3 const*> passmem;
pasmem pm; // neighborhood sequence
for(auto x : pm)
{ 
  // do your stuff as normal but with less typing ;)
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜