Std::function
lastmod 2016-11-23created 2015-03-234 edits
Function wrapper
Class that can wrap any kind of callable element (such as functions and function objects) into a copyable object, and whose type depends solely on its call signature (and not on the callable element type itself).
An object of a function class instantiation can wrap any of the following kinds of callable objects: a function, a function pointer, a pointer to member, or any kind of function object (i.e., an object whose class defines operator(), including closures).
A decay copy of the wrapped callable object is stored internally by the object, which becomes the function's target. The specific type of this target callable object is not needed in order to instantiate the function wrapper class; only its call signature.
The function object can be copied and moved around, and can be used to directly invoke the callable object with the specified call signature (see member operator()).
function objects can also be in a state with no target callable object. In this case they are known as empty functions, and calling them throws a bad_function_call exception.
Performance overhead
- Stackoverflow - What is the performance overhead of std::function?
- Frequently Asked Questions
- Answer provided by Matt Hurd
How much overhead does a call through boost::function incur?
The cost of boost::function can be reasonably consistently measured at around 20ns +/- 10 ns on a modern >2GHz platform versus directly inlining the code.
However, the performance of your application may benefit from or be disadvantaged by boost::function depending on how your C++ optimiser optimises. Similar to a standard function pointer, differences of order of 10% have been noted to the benefit or disadvantage of using boost::function to call a function that contains a tight loop depending on your compilation circumstances.
Troubleshooting
no matching function for call
An error message such as no matching function for call may be printed. Assume the calling code is as follows.
auto callback = std::bind(&MainFrame::onReadAllCallback, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
runner(callback);
In that case, check that it is declared as follows.
using CallbackPrototype = void(int, int64_t, int64_t);
using Functor = std::function<CallbackPrototype>;
// ...
void runner(Functor const & callback);
The key point in the code above is that when Functor is used as an argument, it must be written as (Functor const &).
Favorite site
- class template std::function
- TR1: function
- C++ for Professionals: std::function
- [Recommended] Why does the STL use function objects? (function pointers, function objects, lambdas)