简体   繁体   中英

Cast std function object back to functor struct

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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM