c++ - std::packaged_task 与类内的 std::bind(func, this)

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

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

代码并非仅用于示例目的,在我的实际项目中,我使用 packaged_task 和 std::thread(std::move(task) 等)。

谢谢!

最佳答案

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

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

关于c++ - std::packaged_task 与类内的 std::bind(func, this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28652422/

相关文章:

c++ - 如何使用默认模板参数分离模板类的声明和实现?

c++ - 正则表达式回溯导致堆栈溢出

python - 修改静态变量是线程安全的吗?

c++ - gcc 4.8 或更早版本是否存在关于正则表达式的问题?

java - 如何将线路绑定(bind)到节点?在JAVAFX中

c++ - 最终类的嵌套类是否自动最终?

C++:类/结构是否在编译时初始化过?

C++ 内存泄漏未正确显示

c++: std::bind() 'know' 模板参数是指静态函数还是成员函数?

javascript - 为什么requestAnimFrame需要bind(this)