2

I am creating threadsafe list and i got a problem with calling thread constructor. I got a template class

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

that stores nodes with T data and mylist got member function defined like this

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

that calls f() for every T data in the list. I also got function

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

My problem is that I don't know how to make thread and pass this function to it. I tried like this (mylistis a class name,multithreadlistis an object of mylist<size_t>

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

and i get C2893 Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Types &&...)' and C2672 'std::invoke': no matching overloaded function found

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Square
  • 43
  • 7
  • 1
    I can not reproduce the error with MSVC, Clang or GCC. Can you post an MCVE? – Jorn Vernee Jun 25 '17 at 13:26
  • Does this answer your question? [std thread call template member function of template class: compiler error](https://stackoverflow.com/questions/21617860/std-thread-call-template-member-function-of-template-class-compiler-error) – bers Aug 16 '22 at 10:29

2 Answers2

7

The easiest way is to not bother with [member] function pointers but to rather just use a lambda expression with appropriate captures:

std::thread t([&](){
        multithreadlist.for_each([](auto&& data){ show(data); })
    });
Dietmar Kühl
  • 150,225
  • 13
  • 225
  • 380
0

I don't see the problem. The code below works as expected in

  • Clang 3.8 and 5.0
  • GCC 5.4.1 and 7.1.0

Nevertheless, I would prefer the solution in the other answer myself.

#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();
}
Henri Menke
  • 10,705
  • 1
  • 24
  • 42