Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast std function object back to functor struct

Tags:

c++

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?

like image 950
Anonymous Entity Avatar asked Feb 24 '16 00:02

Anonymous Entity


People also ask

Is std function copyable?

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.

Why did we need to use an std :: function object?

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.

Is std :: function slow?

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.

What is the type of std :: function?

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'.


1 Answers

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);
}
like image 93
Kerrek SB Avatar answered Oct 13 '22 01:10

Kerrek SB