W
W
whoami?root root_toor2016-02-10 18:38:25
C++ / C#
whoami?root root_toor, 2016-02-10 18:38:25

How to use templates when creating c++11 std::thread threads?

There is a code:

#include <iostream>
#include <algorithm>
#include <thread>

template<typename T>
T func(T& tid) {
    std::cout << "Thread says: " << tid << std::endl;
}

int main()
{
    std::thread t(func,35);
    t.join();

   return 0;
}

An error is thrown:
main.cpp:17: ошибка: no matching function for call to 'std::thread::thread(<unresolved overloaded function type>, int)'
     std::thread t(func,35);
                          ^

Without a template, the code works as it should. Judging by what is written, the compiler does not know which version of the function to call. A Google friend doesn't want to help... even though the standard has been adopted 6! years ago, there was not much information on using streams (using templates) ...
of course, you can do without templates, but I want to know what the problem is. I will be grateful for your help!)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AtomKrieg, 2016-02-10
@1q2w1q2w

Help the compiler determine the function type to instantiate

#include <iostream>
#include <algorithm>
#include <thread>

template<typename T>
T func (T& tid) {
  std::cout << "Thread says: " << tid << std::endl;
  return tid;
}

int main ()
{
  unsigned val = 35;
  std::thread t (func<decltype(val)>, val);
  t.join ();

  system ("pause");
  return 0;
}

D
Dmitry Fedorenko, 2016-02-10
@fdsmerlin


this is how #include works
#include
using namespace std;
template void func(T& id)
{
std::cout << "Thread cout : " << id << std::endl;
}
int main()
{
std::thread t (std::bind(&func,32));
t.join();
return 0;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question