3

On the program below, I'm trying to create a packaged_task with a member function:

#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; } 

Unfortunately the attempt results in an error.

How can this be done?

1
  • 1
    The problem is not your use of packaged_task, it's your use of bind. Remove the packaged_task and try calling bnd(1) and see what happens. Commented Mar 11, 2015 at 19:57

2 Answers 2

3

by adding up a placeholder like:

auto bnd = std::bind(&S::calc, s, std::placeholders::_1) 
Sign up to request clarification or add additional context in comments.

Comments

1

std::bind is quirky.

Replace your use of std::bind with:

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? 

and now auto bnd = bind_member(s, S::calc); should make your code work.

There are few situations where a lambda isn't a better idea than std::bind, especially by C++14. In C++11, there are some corner cases, but even then I usually prefer to write my own binders without the quirks of std::bind.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.