2

I have prepared a small snippet isolating my problem here. Here it is :

#include <stdio.h>    
#include <future>
#include <functional>

class foo
{
    public:
        foo(int a, int b) : m_a(a), m_b(b) {}
        int somefunc(int a, int b) { printf("foo w0w : %d, %d", a == m_a, b == m_b); return 0; }
        void meow() {
            std::packaged_task<int(int, int)> task( std::bind(&foo::somefunc, this) );
            task(10, 12);
            return;
        }


    private:
        int m_a, m_b;
};


int main(void)
{
    foo bar(1,2);
    return 0;
}

GCC doesn't want to compile this, stating :

In file included from c:\mingw\include\c++\4.8.3\thread:39:0,
                 from xcc.cpp:7:
c:\mingw\include\c++\4.8.3\functional: In instantiation of 'struct std::_Bind_simple<std::reference_wrapper<std::_Bind<std::_Mem_fn<int (foo::*)(int, int)>(foo*)> >(int, int)>':
c:\mingw\include\c++\4.8.3\future:1276:55:   required from 'void std::__future_base::_Task_state<_Fn, _Alloc, _Res(_Args ...)>::_M_run(_Args ...) [with _Fn = std::_Bind<std::_Mem_fn<int (foo::*)(int, int)>(foo*)>; _Alloc = std::allocator<int>; _Res = int; _Args = {int, int}]'
xcc.cpp:40:1:   required from here
c:\mingw\include\c++\4.8.3\functional:1697:61: error: no type named 'type' in 'class std::result_of<std::reference_wrapper<std::_Bind<std::_Mem_fn<int (foo::*)(int, int)>(foo*)> >(int, int)>'
       typedef typename result_of<_Callable(_Args...)>::type result_type;
                                                             ^
c:\mingw\include\c++\4.8.3\functional:1727:9: error: no type named 'type' in 'class std::result_of<std::reference_wrapper<std::_Bind<std::_Mem_fn<int (foo::*)(int, int)>(foo*)> >(int, int)>'
         _M_invoke(_Index_tuple<_Indices...>)
         ^

I'm near a burnout trying to make this work. Compiler error message is complete garbage to me, thus I'm completely lost. Please help how to achieve this.

Not the code is only for example purpose, in my real project I'm ofc using packaged_task with std::thread(std::move(task), etc etc).

Thanks!

T.C.
  • 133,968
  • 17
  • 288
  • 421
Yannick
  • 830
  • 7
  • 27
  • 1
    `[this](int a, int b){ return somefunc(a, b); }` is more readable, about the same number of keys to type as `std::bind(&foo::somefunc, this, _1, _2)`, and will give better error messages when you make mistakes. I suggest you prefer lambdas to `std::bind` whenever possible. – Casey Feb 22 '15 at 05:28

1 Answers1

4

You need two placeholders for the arguments you're going to call it with:

using namespace std::placeholders;
std::packaged_task<int(int, int)> task(std::bind(&foo::somefunc, this, _1, _2));
David G
  • 94,763
  • 41
  • 167
  • 253