Let's assume I want to pass a function object created by std::bind
by reference to a funktion:
void myCallback(int i, int j)
{
std::cout << "toCall , i=" << i << " j=" << j;
}
void worker(std::function<void(int)> & callback)
{
callback(111);
}
int main(int argc, char** argv)
{
auto foo = std::bind(myCallback, std::placeholders::_1, 222);
worker(foo);
}
This does not compile
Severity Code Description Project File Line Suppression State Error C2664 'void worker(std::function &)': cannot convert argument 1 from 'std::_Binder &,int>' to 'std::function &' asn1test_1 D:.....\asn1test_1.....cpp 302
However, passing by value works:
void worker(std::function<void(int)> callback)
{
callback(111);
}
When I avoid "auto
" and use instead
std::function<void(int)> foo = std::bind(myCallback, std::placeholders::_1, 222);
it works both with passing by reference or by value.
Q1: Why this behavior?
Q2: What would be the "right" way or datatype to pass an object created by std::bind
to a function?
It should be:
because then implicit conversion from
foo
to temporarystd::function
object can be made.