让我们想象一下,我定义了一个简单的函数引用包装器,如下所示:
struct wrapper {
std::function<void(void)>& fct;
wrapper(std::function<void(void)>& _fct) : fct{_fct}{
fct();
};
};
当然,在现实中它比这个更复杂,但是我简化了它来说明这个问题。
然后,我想创建包含函数引用包装器的测试对象:
struct test {
wrapper myWrapper;
test() : myWrapper{std::bind(&test::boom, this)}{};
void boom() {
std::cout << "boom()" << std::endl;
}
};
在test
对象实例化时,我得到以下错误(尝试一下这里):
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&
**?** ()吗?
发布于 2020-07-17 14:37:07
有了这个“类型化绑定”的“原始”实现,我可以问:保存"test*“指针的内存将被包装器存储在哪里?那么bindex如何知道哪种类型的->first应该被转换到哪里呢?这个索引应该被删除吗?
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} ) {};
. . .
}
https://stackoverflow.com/questions/62962144
复制