c++ - 'std::thread' 的初始化没有匹配的构造函数

标签 c++ multithreading c++14

我一直在研究一个相当简单的设施:并发 for 循环构造,它采用输入元素列表、输出 vector 和根据输入元素计算输出元素的函数。

我有这个无法编译的片段:

            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: error: no matching constructor for initialization of 'std::thread'
                    thread_vector.push_back(std::thread(thread_do, 
                                            ^           ~~~~~~~~~~

但是,我不知道如何修复它。试图在 之前添加 & thread_do /附加 <In, Out> ,但无济于事。

最佳答案

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

#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 的构造函数无法自动推导模板参数。你必须明确。

关于c++ - 'std::thread' 的初始化没有匹配的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38191014/

相关文章:

c++ - 如何通过 C API 传递带捕获的 std::function?

c++ - 从派生类调用重载函数。

使用缓冲区和线程进行 Java TCP byteArray 传输

c# - C# .NET 中具有多个监听器的线程一次性变量赋值

java - 操作系统的Semaphore和Java给出的Semaphore有什么区别?

c++ - 命名模板参数是在最新标准中还是在现代编译器中实现的?

c++ - 如何设置包含在 CMake/CLion 中的子目录?

c# - 如何强制 .NET (C#) 使用方法的非泛型重载?

c++ - 空终止字符串,它真的是由标准规定的吗?

c++ - 如何在 C++ 中生成范围有限的字符串的哈希码?