Capturing a broken function

I have a getTotal function:

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

where the second argument is a bool function that indicates which elements of the hitMap container should be added to the total.

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

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

but this is not so:

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

I get an 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 [§or] and [=sector] , but that didn't make any difference.

What am I doing wrong?

+7
source share
2 answers

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

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

A lambda function with a grip is not what you expect, you can use the following methods:

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

or

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

getTotal based getTotal has better performance. More details .

+3
source

All Articles