int func(int x){return x;}
...
std::function<int(int)> x = std::bind(func, std::placeholders::_1);
x(123);
- Does
x(123)actually call theoperator()of the functor whichstd::functiongenerated which in turn calls theoperator()of the functor whichstd::bindgenerated which finally callsfunc? Does this get optimized into something as optimal as callingfunc(123)? - Where does the functor live which
std::bindgenerates? In what scope? And how doesstd::bindname it? (can there be name collisions) - Can lambdas replace all uses of
std::bind? - Is
std::bindas optimal as implementing it as a lambda instead? - What’s up with the syntax of the template argument of
std::function? How does that get parsed and how can I use that template argument syntax elsewhere?
I wouldn’t describe the
operator()ofstd::functionas ‘generated’ (it’s a regular member), but otherwise that is a good description. Optimizations are up to your compiler, but be warned that to optimize the indirection ofstd::function(which requires the use of type erasure) a compiler may need to perform heroics.The call to
std::bindreturns a functor of unspecified type, and a copy of that functor is stored inside thexobject. This copy will live as long asxitself. There is no name involved so I’m not sure what you mean by that.No. Consider
auto bound = std::bind(functor, _1);wherefunctoris a type with an overloadedoperator(), let’s say onlongandint. Thenbound(0L)doesn’t have the same effect asbound(0)and you can’t replicate that with a lambda.This is up to the compiler. Measure yourself.
It’s a function type. Perhaps you’re already familiar with the syntax for pointers/references to functions:
void(*)(),int(&)(double). Then just remove the pointer/reference out of the type, and you just have a function type:void(),int(double). You can use those like so: