【问题标题】:How to create thread with template member function of a template object in c++如何在c ++中使用模板对象的模板成员函数创建线程
【发布时间】:2017-11-28 12:32:44
【问题描述】:

我正在创建线程安全列表,但调用线程构造函数时遇到问题。 我有一个模板类

template <typename T>
class mylist{...}

用 T 数据存储节点,mylist 的成员函数定义如下

template <typename FUNC>
void for_each(FUNC f){...}

为列表中的每个 T 数据调用 f()。 我也有功能

template<typename T> 
void show(T data) 
{cout<<data<<", ";}

我的问题是我不知道如何制作线程并将这个函数传递给它。 我试过这样(mylist是类名,multithreadlistmylist&lt;size_t&gt;的对象

std::thread t1(&mylist<size_t>::for_each<void(*)(size_t)>, &multithreadlist, show<size_t>);

我得到 C2893 无法专门化函数模板“未知类型 std::invoke(_Callable &&,_Types &&...)”和 C2672“std::invoke”:找不到匹配的重载函数

【问题讨论】:

  • 我无法使用 MSVC、Clang 或 GCC 重现错误。你能发布一个 MCVE 吗?

标签: c++ multithreading templates syntax constructor


【解决方案1】:

最简单的方法是不要使用 [member] 函数指针,而只需使用带有适当捕获的 lambda 表达式:

std::thread t([&](){
        multithreadlist.for_each([](auto&& data){ show(data); })
    });

【讨论】:

    【解决方案2】:

    我没有看到问题。下面的代码在

    中按预期工作
    • Clang 3.8 和 5.0
    • GCC 5.4.1 和 7.1.0

    尽管如此,我自己更喜欢其他答案中的解决方案。

    #include <iostream>
    #include <thread>
    #include <vector>
    
    template <typename T>
    class mylist
    {
      std::vector<T> m_list;
    public:
      mylist(int n) : m_list(n)
      {
        for (int i = 0; i < n; ++i)
          m_list[i] = i;
      }
    
      template < typename FUNC >
      void for_each(FUNC f)
      {
        for (auto const& p : m_list)
          f(p);
      }
    };
    
    template<typename T> 
    void show(T data)
    {
      std::cout << data << ", ";
    }
    
    int main()
    {
      mylist<size_t> multithreadlist{5};
      std::thread t1(&mylist<size_t>::for_each<void(*)(size_t)>, multithreadlist, show<size_t>);
      t1.join();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-11
      • 2012-11-09
      • 1970-01-01
      • 2013-09-23
      • 2010-10-04
      • 1970-01-01
      相关资源
      最近更新 更多