简体   繁体   English

将std函数对象转换回functor结构

[英]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? 有没有办法稍后将f Functor转换为Functor类型?

The target member function is std::function 's type-unerasing cast. target成员函数是std::function的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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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