给定一个函数
void MyFunction(std::unique_ptr<int> arg);
不可能(MSVC 2012)创建像这样的仿函数
std::function<void(std::unique_ptr<int>)> f = std::bind(&MyFunction, std::placeholders::_1);
问题不在于绑定(bind) - 使用 auto f = std::bind(...)
可以。此外,使用 shared_ptr
也有效
- 为什么不允许使用 unique_ptr?
- 这是 MSVC 问题还是一般的 C++11 限制?
- 是否有不更改函数定义的解决方法?
最佳答案
下面的代码使用 gcc 4.8 编译良好。你会注意到 如果没有用 move 调用“g”(将左值转换为右值), 代码无法编译。如前所述,绑定(bind)成功是因为 失败仅在调用 operator()( ... ) 时发生,因为 unique_ptr 不可复制的事实。调用“f”是允许的,因为 shared_ptr 有一个复制构造函数。
#include <functional>
#include <memory>
void foo1( std::shared_ptr<int> ){}
void foo2( std::unique_ptr<int> ){}
int main()
{
using namespace std::placeholders;
std::function<void(std::shared_ptr<int>)> f = std::bind( foo1, _1 );
std::function<void(std::unique_ptr<int>)> g = std::bind( foo2, _1 );
std::unique_ptr<int> i( new int(5) );
g( move( i ) ); //Requires the move
std::shared_ptr<int> j( new int(5) );
f( j ); //Works fine without the move
return 0;
}
关于c++ - 带有 unique_ptr 参数的 std::function,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17141185/