假设我有一个functor s,它是不可复制但可移动的,我怎样才能将它存储在std :: function中?即,如何编译以下代码?(使用gcc 4.6)
#include <functional>
#include <iostream>
struct S
{
S() = default;
S(S const&) = delete;
S& operator=(S const&) = delete;
S(S&&) { }
void operator()() { }
};
std::function<void()> func;
void make_func()
{
S s;
func = std::bind(std::move(s)); // This won't compile
}
int main()
{
make_func();
}
Run Code Online (Sandbox Code Playgroud)
小智 2
据我了解该标准,std::function应该是可以复制的。因此,你无法直接实现你想要的。
不过,我猜你可以使用一些自定义包装器。事情会是这样的:
std::shared_ptr实际的函子;shared_ptr包装器和析构函数的复制构造函数由复制构造函数/析构函数简单处理;operator()因为包装器将智能指针取消引用到真正的函子并委托给operator()它。| 归档时间: |
|
| 查看次数: |
2177 次 |
| 最近记录: |