c++ - 使用变量类型的 std::function 运行线程

标签 c++ c++11 stdthread

我想在一个单独的线程中启动一个 std::function 类型。 我的代码目前看起来像这样:

struct bar
{
    std::function<void(int,int)> var;
};

struct foo
{
    bar* b;

    foo()
    {
        std::thread t(b->var); //Error attempt to use a deleted function
    }
};

为什么我会在这里尝试使用已删除的函数?

最佳答案

您的变量 b->var 是一个带有两个参数的函数。您需要发送这些参数才能使其工作。

struct bar
{
  std::function<void(int,int)> var;
};

struct foo
{
   bar* b;
   foo()
   {
      std::thread t(b->var, 76, 89); // will call b->var(76, 89)
   }
};

关于c++ - 使用变量类型的 std::function 运行线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36023836/

相关文章:

c++ - 使图形发光/光晕

c++ - 在编译时防止 header 包含在某些文件中?

c++ - 指向成员函数的指针的大小变化很大

c++ - 将变量参数列表转发到模拟 std::thread

c++ - 在多个线程中使用 std::cout

c++ - 在 std::thread 中运行时,C++ 成员变量的生命周期是多少?

c++ - 为什么到目前为止复合文字还不是 C++ 的一部分?

c++ - 使用模板和右值引用的重载解决方案

c++ - 从 C++ 模板中的非 const 左值引用推导出 const 左值引用

c++ - 在C++线程对象中重新绑定(bind)*this, move 构造函数, move 赋值