Std::function
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
no matching function for call
와 같은 에러 메시지가 출력될 수 있다. 호출하는 코드가 아래와 같다고 가정한다.
auto callback = std::bind(&MainFrame::onReadAllCallback, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
runner(callback);
그렇다면 아래와 같이 선언되었는지 확인해야 한다.
using CallbackPrototype = void(int, int64_t, int64_t);
using Functor = std::function<CallbackPrototype>;
// ...
void runner(Functor const & callback);
위의 코드에서 중요한 점은 Functor
를 인자로 사용할 경우 (Functor const &)
와 같이 사용해야 한다.