首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >通过std绑定向成员函数引用std函数

通过std绑定向成员函数引用std函数
EN

Stack Overflow用户
提问于 2020-07-17 21:43:41
回答 1查看 152关注 0票数 0

让我们想象一下,我定义了一个简单的函数引用包装器,如下所示:

代码语言:javascript
运行
复制
struct wrapper {
    std::function<void(void)>& fct;
    
    wrapper(std::function<void(void)>& _fct) : fct{_fct}{
        fct();    
    };
};

当然,在现实中它比这个更复杂,但是我简化了它来说明这个问题。

然后,我想创建包含函数引用包装器的测试对象:

代码语言:javascript
运行
复制
struct test {
    wrapper myWrapper;
    
    test() : myWrapper{std::bind(&test::boom, this)}{};
    
    void boom() {
        std::cout << "boom()" << std::endl;
    }
    
};

test对象实例化时,我得到以下错误(尝试一下这里):

代码语言:javascript
运行
复制
 cannot bind non-const lvalue reference of type 'std::function<void()>&' to an rvalue of type 'std::function<void()>'

这是可以理解的,因为std::bind对象是一个临时的(rvalue),我不能引用它(我也尝试过没有std::bind,没有更好的结果)。另一方面,能够以std::function的形式引用非静态成员函数似乎很容易,但我不能把它放在心上。

有什么简单的方法可以将非静态成员函数引用为std::function&**?** ()吗?

EN

回答 1

Stack Overflow用户

发布于 2020-07-17 22:37:07

有了这个“类型化绑定”的“原始”实现,我可以问:保存"test*“指针的内存将被包装器存储在哪里?那么bindex如何知道哪种类型的->first应该被转换到哪里呢?这个索引应该被删除吗?

代码语言:javascript
运行
复制
struct bindx : pair<void(test::*)(void), test*> {
    using pair<void(test::*)(void), test*>::pair;
    void operator()() { (second->*first)(); }
};

struct wrapper {
    bindx f_;
    
    wrapper(bindx f) : f_{f}{
        f_();    
    };
};

struct test {
    wrapper myWrapper;
    
    test() : myWrapper( bindx{&test::boom, this} ) {};
     . . .
}

http://coliru.stacked-crooked.com/a/a40f432aad928908

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62962144

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档