std::packaged_task std::bind(func, this) 在 class 内

std::packaged_task with std::bind(func, this) within class

我准备了一个小片段来隔离我的问题。 在这里:

#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++.8.3\thread:39:0,
                 from xcc.cpp:7:
c:\mingw\include\c++.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++.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++.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++.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...>)
         ^

为了完成这项工作,我快筋疲力尽了。编译器错误消息对我来说完全是垃圾,因此我完全迷路了。请帮助如何实现这一目标。

不是代码仅用于示例目的,在我的真实项目中,我使用 packaged_task 和 std::thread(std::move(任务)等)。

谢谢!

您需要两个占位符来表示您要调用它的参数:

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