Reputation: 295
Cannot pass function as argument to std::thread
when class is defined as template.
compiler: GCC 4.8.2 language: C++11
code:
//---------test.h-----------------------
#ifndef TEST_H
#define TEST_H
#include <iostream>
#include <thread>
using namespace std;
template <class T>
class test
{
public:
test();
void thr(T n);
void testThread();
};
#endif // TEST_H
//---------test.cpp-----------------------
#include "test.h"
template <class T>
test<T>::test()
{
}
template <class T>
void test<T>::thr(T n)
{
cout << n << endl;
}
template <class T>
void test<T>::testThread()
{
T n = 8;
thread t(thr, n);
t.join();
}
//---------main.cpp-----------------------
#include <iostream>
using namespace std;
#include "test.h"
#include "test.cpp"
int main()
{
test<double> tt;
tt.testThread();
return 0;
}
compiler error:
In file included from ../std_threads/main.cpp:5:0:
../std_threads/test.cpp: In instantiation of 'void test<T>::testThread() [with T = double]':
../std_threads/main.cpp:10:19: required from here
../std_threads/test.cpp:19:20: error: no matching function for call to 'std::thread::thread(<unresolved overloaded function type>, double&)'
thread t(thr, n);
^
../std_threads/test.cpp:19:20: note: candidates are:
In file included from ../std_threads/test.h:4:0,
from ../std_threads/main.cpp:4:
/usr/include/c++/4.8.2/thread:133:7: note: std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (test<double>::*)(double); _Args = {double&}]
thread(_Callable&& __f, _Args&&... __args)
^
/usr/include/c++/4.8.2/thread:133:7: note: no known conversion for argument 1 from '<unresolved overloaded function type>' to 'void (test<double>::*&&)(double)'
/usr/include/c++/4.8.2/thread:128:5: note: std::thread::thread(std::thread&&)
thread(thread&& __t) noexcept
^
/usr/include/c++/4.8.2/thread:128:5: note: candidate expects 1 argument, 2 provided
/usr/include/c++/4.8.2/thread:122:5: note: std::thread::thread()
thread() noexcept = default;
^
/usr/include/c++/4.8.2/thread:122:5: note: candidate expects 0 arguments, 2 provided
make: *** [main.o] Error 1
20:48:35: The process "/usr/bin/make" exited with code 2.
Error while building/deploying project std_threads (kit: Desktop)
When executing step 'Make'
Upvotes: 2
Views: 2383
Reputation: 227608
You need to fully specify the member function name and pass an argument for the implicit first parameter of the non-static member function:
thread t(&test<T>::thr, this, n);
See std::thread
of a member function.
Upvotes: 5
Reputation: 254751
Two problems:
&
and qualify the function name with the class name. Member functions names don't convert to pointers in the same way as non-member function names.So in this case, you probably want
thread t(&test<T>::thr, this, n);
Upvotes: 4