在下面的程序中,我正在尝试使用成员函数创建一个packaged_task:
#include <future>
using namespace std;
struct S
{
int calc(int& a)
{
return a*a;
}
};
int main()
{
S s;
auto bnd = std::bind(&S::calc, s);
std::packaged_task<int(int&)> task( bnd);
return 0;
}
不幸的是,该尝试导致错误。
如何才能做到这一点?
最佳答案
std::bind
是古怪的。
将对std::bind
的使用替换为:
template<class T, class Sig>
struct bound_member;
template<class T, class R, class...Args>
struct bound_member<T, R(Args...)> {
T* t;
R(T::*m)(Args...);
R operator()(Args...args)const {
return (t->*m)(std::forward<Args>(args)...);
};
template<class T, class R, class...Args>
bound_member<T,R(Args...)> bind_member( T* t, R(T::*m)(Args...) ) {
return {t,m};
}
template<class T, class R, class...Args>
bound_member<T,R(Args...)> bind_member( T& t, R(T::*m)(Args...) ) {
return {&t,m};
}
template<class T, class R, class...Args>
bound_member<T,R(Args...)> bind_member( T&& t, R(T::*m)(Args...) )
=delete; // avoid lifetime issues?
现在
auto bnd = bind_member(s, S::calc);
应该可以使您的代码正常工作。在少数情况下,lambda并不是比
std::bind
更好的主意,尤其是在C++ 14中。在C++ 11中,有一些极端的情况,但是即使那样,我通常还是更喜欢编写自己的活页夹,而没有std::bind
的怪癖。关于c++ - 如何使用成员函数创建packaged_task?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28995421/