如何使用成员函数创建packaged_task?

时间:2015-03-11 19:15:37

标签: c++ multithreading c++11 packaged-task

在下面的程序中,我正在尝试使用成员函数创建一个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;
}

不幸的是,尝试会导致错误。

如何做到这一点?

2 个答案:

答案 0 :(得分:3)

添加一个占位符,如:

auto bnd = std::bind(&S::calc, s, std::placeholders::_1)

答案 1 :(得分:1)

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的怪癖。

相关问题