【问题标题】:no matching constructor for initialization of 'std::thread''std::thread' 的初始化没有匹配的构造函数
【发布时间】:2016-11-06 13:22:59
【问题描述】:

我一直在研究一个相当简单的工具:并发 for 循环构造,它采用输入元素列表、输出向量和从输入元素中计算输出元素的函数.

我有这个无法编译的 sn-p:

            template<class In, class Out>
            void thread_do(net::coderodde::concurrent::queue<In>& input_queue,
                           Out (*process)(In in),
                           std::vector<Out>& output_vector)
            {
                // Pop the queue, process, and save result.
                ...
            }


                for (unsigned i = 0; i < thread_count; ++i) 
                {
                    thread_vector.push_back(std::thread(thread_do, 
                                                        input_queue,
                                                        process,
                                                        output_vector));
                }

我使用 -std=c++14。

./concurrent.h:129:45:错误:没有匹配的构造函数用于初始化“std::thread” thread_vector.push_back(std::thread(thread_do, ^ ~~~~~~~~~~

但是,我不知道如何解决它。尝试在 thread_do/附加 &lt;In, Out&gt; 前添加 &amp;,但无济于事。

【问题讨论】:

  • thread_do 既是模板函数又是类方法。 std::thread 的构造函数需要反映这一点。
  • 哇,方式代码太多了。本月到目前为止,您一直在调试的 minimal reproducible example 在哪里?
  • “但是,我不知道如何解决它。尝试在 thread_do/appending 前面加上 &,但没有用。” 你可以尝试阅读文档,这确实应该是您的第一步,而不是胡乱猜测。
  • @LightnessRacesinOrbit 接下来你建议阅读整个标准吗?
  • @coderodde:想想你这样做时会学到的所有其他有趣的东西。花几天时间浏览文档是一件好的事情。

标签: c++ multithreading c++14


【解决方案1】:

这个最小的完整示例(提示)向您展示了如何在另一个线程中调用模板成员函数。

#include <thread>

struct X
{

  template<class A, class B> void run(A a, B b)
  {
  }

  template<class A, class B>
  void run_with(A a, B b)
  {
    mythread = std::thread(&X::run<A, B>, this, a, b);
  }

  std::thread mythread;
};

int main()
{
  X x;
  x.run_with(10, 12);
  x.mythread.join();
}

请注意std::thread 的构造函数不能自动推断模板参数。你必须是明确的。

【讨论】:

    【解决方案2】:

    你需要实例化你的函数:

    thread_vector.push_back(std::thread(thread_do<In, Out>,     // you need to instantiate your template function 
                                        std::ref(input_queue),  // pass parameters by ref 
                                        std::ref(process),      // - // -
                                        std::ref(output_vector))// - // -
                                        );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      • 2017-06-27
      相关资源
      最近更新 更多