Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capturing breaks my lambda function [duplicate]

Tags:

c++

c++11

lambda

I have a function getTotal:

int getTotal( const HitMap& hitMap, bool( *accept)(int chan) )

where the second argument is a bool function specifying which members of the container hitMap should be added to the total.

I'm trying to call it with a lambda. This works:

auto boxresult =
getTotal(piHits, [](int pmt)->bool
{ return (pmt/100) == 1;} );

but this doesn't:

int sector = 100;
auto boxresult =
getTotal(piHits, [sector](int pmt)->bool
{ return (pmt/sector) == 1;} );

I get the error

cannot convert ‘main(int, char**)::<lambda(int)>’ to ‘bool (*)(int)’
for argument ‘2’ to ‘int getTotal(const HitMap&, bool (*)(int))’

from my compiler (GCC 4.6.3). I tried [&sector] and [=sector] but it didn't make any difference.

What am I doing wrong?

like image 356
paco_uk Avatar asked Apr 22 '13 11:04

paco_uk


People also ask

How do you duplicate a lambda function?

When editing a lambda function, you can go Actions > Export Function > Download deployment package. This downloads a . zip file of the function. This duplicates the code and npm modules etc...

What does it mean to Lambda capture this?

A lambda is a syntax for creating a class. Capturing a variable means that variable is passed to the constructor for that class. A lambda can specify whether it's passed by reference or by value.

How do you stop Lambda invocation?

If you want to stop future invocations a simple way to do this is by removing the related permission from the IAM role associated with your Lambda. You can find a link to the IAM role in the permissions tab of the Lambda.

Can a Lambda capture itself?

But a lambda cannot be recursive, it has no way to invoke itself. A lambda has no name and using this within the body of a lambda refers to a captured this (assuming the lambda is created in the body of a member function, otherwise it is an error).


2 Answers

When a lambda has a capture clause it can no longer be treated as a function pointer. To correct, use std::function<bool(int)> as the argument type for getTotal():

int getTotal( const HitMap& hitMap, std::function<bool(int)> accept)
like image 115
hmjd Avatar answered Sep 29 '22 03:09

hmjd


The lambda function with capturing is not what you expect, you can use these ways:

template <typename F>
int getTotal( const HitMap& hitMap, F accept )
{

}

or

int getTotal( const HitMap& hitMap, std::function<bool(int)> accept )
{

}

The template based getTotal has better performance. Read more.

like image 34
masoud Avatar answered Sep 29 '22 02:09

masoud