Is there any differences?
Which is the best way to "save/transfer" function?
function<void(int)> fcn = [](int par) {std::cout<<"fcn: "<<par<<std::endl; }; void(*fcn_a)(int) = [](int par) {std::cout<<"fcn_a: "<<par<<std::endl; }; fcn(12); fcn_a(12);

- 1,816
- 4
- 21
- 31
2 Answers
std::function
is more generic - you can store in it any callable object with correct signature (function pointer, method pointer, object with operator()
) and you can construct std::function
using std::bind.
Function pointer can only accept functions with correct signature but might be slightly faster and might generate slightly smaller code.

- 1,981
- 14
- 19
In the case of a non-capturing lambda, using a function pointer would be faster than using std::function
. This is because std::function
is a far more general beast and uses type-erasure to store the function object passed to it. It achieves this through type-erasure, implying that you end up with a call to operator()
being virtual.
OTOH, non-capturing lambdas are implicitly convertible to the corresponding function pointer. If you need a full-fledged closure however, you will have to assign the lambda to std::function
, or rely on type deduction through templates, whenever possible.

- 16,391
- 3
- 44
- 59