2

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

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

如何才能做到这一点?

4

2 回答 2

3

通过添加一个占位符,例如:

auto bnd = std::bind(&S::calc, s, std::placeholders::_1)
于 2015-03-11T19:53:15.187 回答
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.

于 2015-03-11T20:23:07.937 回答