What is the advantage of std::function<T1(T2)>
over the original T1 (*)(T2)
?
std::function
can hold more than function pointers, namely functors.
#include <functional>
void foo(double){}
struct foo_functor{
void operator()(float) const{}
};
int main(){
std::function<void(int)> f1(foo), f2((foo_functor()));
f1(5);
f2(6);
}
Live example on Ideone.
As the example shows, you also don't need the exact same signature, as long as they are compatible (i.e., the parameter type of std::function
can be passed to the contained function / functor).
std::function
can hold function objects (including lambdas), as well as function pointers with the correct signature. So it is more versatile.
Apart from the cleaner look and a more descriptive syntax, std::function
can store any callable object:
Not to mention that storing, copying, and binding objects to member functions is much easier and more intuitive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With