In this scenario:
struct Holder {
std::function<void()> f;
};
struct Functor { void operator()(){ /**/ } };
int main() {
Holder = { Functor{} };
//...
Is there a way to later cast f
back to a Functor
type?
Instances of std::function can store, copy, and invoke any CopyConstructible Callable target -- functions (via pointers thereto), lambda expressions, bind expressions, or other function objects, as well as pointers to member functions and pointers to data members.
It lets you store function pointers, lambdas, or classes with operator() . It will do conversion of compatible types (so std::function<double(double)> will take int(int) callable things) but that is secondary to its primary purpose.
Code wrapped into std::function is always slower than inlining code directly into calling place. Especially if your code is very short, like 3-5 CPU instructions.
std::function is a type erasure object. That means it erases the details of how some operations happen, and provides a uniform run time interface to them. For std::function , the primary1 operations are copy/move, destruction, and 'invocation' with operator() -- the 'function like call operator'.
The target
member function is std::function
's type-unerasing cast. You'll need to know the target type:
#include <cassert>
#include <functional>
struct Functor { void operator()(){ /**/ } };
int main()
{
std::function<void()> f = Functor();
Functor * p = f.target<Functor>();
assert(p != nullptr);
}
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