【发布时间】:2015-11-19 08:37:45
【问题描述】:
我需要将结构与已删除的复制构造函数绑定到一个函数。我已将我想要实现的目标简化为以下最小示例:
struct Bar {
int i;
Bar() = default;
Bar(Bar&&) = default;
Bar(const Bar&) = delete;
Bar& operator=(const Bar&) = delete;
};
void foo(Bar b) {
std::cout << b.i << std::endl;
}
int main()
{
Bar b;
b.i = 10;
std::function<void()> a = std::bind(foo, std::move(b)); // ERROR
a();
return 0;
}
从编译器中我得到的只有哀嚎和咬牙切齿:
test.cpp:22:27: error: no viable conversion from 'typename _Bind_helper<__is_socketlike<void (&)(Bar)>::value, void (&)(Bar), Bar>::type' (aka '_Bind<__func_type (typename decay<Bar>::type)>') to 'std::function<void ()>'
std::function<void()> a = std::bind(foo, std::move(b));
^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.1.0/../../../../include/c++/5.1.0/functional:2013:7: note: candidate constructor not viable: no known conversion from 'typename _Bind_helper<__is_socketlike<void (&)(Bar)>::value, void (&)(Bar),
Bar>::type' (aka '_Bind<__func_type (typename decay<Bar>::type)>') to 'nullptr_t' for 1st argument
function(nullptr_t) noexcept
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.1.0/../../../../include/c++/5.1.0/functional:2024:7: note: candidate constructor not viable: no known conversion from 'typename _Bind_helper<__is_socketlike<void (&)(Bar)>::value, void (&)(Bar),
Bar>::type' (aka '_Bind<__func_type (typename decay<Bar>::type)>') to 'const std::function<void ()> &' for 1st argument
function(const function& __x);
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.1.0/../../../../include/c++/5.1.0/functional:2033:7: note: candidate constructor not viable: no known conversion from 'typename _Bind_helper<__is_socketlike<void (&)(Bar)>::value, void (&)(Bar),
Bar>::type' (aka '_Bind<__func_type (typename decay<Bar>::type)>') to 'std::function<void ()> &&' for 1st argument
function(function&& __x) : _Function_base()
^
/usr/bin/../lib/gcc/x86_64-linux-gnu/5.1.0/../../../../include/c++/5.1.0/functional:2058:2: note: candidate template ignored: substitution failure [with _Functor = std::_Bind<void (*(Bar))(Bar)>]: no matching function for call to object of
type 'std::_Bind<void (*(Bar))(Bar)>'
function(_Functor);
^
1 error generated.
所以我想问一下是否有任何解决方法可以让我将 Bar 绑定到 foo 同时保持 Bar 只移动。
编辑:
还要考虑以下代码,其中变量b 在调用a 之前结束:
int main()
{
std::function<void()> a;
{
Bar b;
b.i = 10;
a = std::bind(foo, std::move(b)); // ERROR
}
a();
return 0;
}
【问题讨论】: