std :: packaged_task在类中使用std :: bind(func,this)

时间:2015-02-21 23:02:33

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

我准备了一个小片段来解决我的问题。 这是:

#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不想编译这个,说明:

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...>)
         ^

我正在努力使这项工作倦怠。编译器错误消息对我来说是完全垃圾,因此我完全丢失了。请帮助如何实现这一目标。

不是代码只是出于示例目的,在我的实际项目中我使用带有std :: thread(std :: move(task)等等的packaged_task)。

谢谢!

1 个答案:

答案 0 :(得分:4)

您需要使用两个占位符来调用它:

using namespace std::placeholders;
std::packaged_task<int(int, int)> task(std::bind(&foo::somefunc, this, _1, _2));