Question

I created a lambda expression inside my std::for_each call.

In it there is code like this one, but I have building error telling me that

error: expected primary-expression before ‘return’
error: expected `]' before ‘return’

In my head I think that boost-lambda works mainly with functors, so since return statement it isn't like that, calling it doesn't work.

Do you know what it is and how to fix it?

Thanks AFG

namespace bl = boost::lambda;
int a, b;
bl::var_type::type a_( bl::var( a ) );
bl::var_type::type b_( bl::var( b ) );

std::for_each( v.begin(), v.end(), (
// ..do stuff here
if_(  a_ > _b_ )
[
std::cout << _1,
 return
]
));
Was it helpful?

Solution

You cannot use return instruction inside lambda expression. Use constructions like if_then_else_return. They offer syntax that allows producing results. But in your case return is not even required, just throw it away.

OTHER TIPS

just forget boost-lambda and use the new standard C++ lambda expression instead.

Explanation & Example

@MBZ is right, use C++11 (but not lambda in this case).

Here is your code with C++11:

int a, b;
std::vector<int> v;
for(int e : v)
{
  if(a > b)
    std::cout << e;
}

Of course you could do the same with lambdas, but why complicating it like the code below?

int a, b;
std::vector<int> v;
std::for_each(v.begin(), v.end(), 
  [&a,&b](int e)
  {
    if(a > b)
      std::cout << e;
  }
);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top