[英]C++11 run templated class function with std::thread
當類定義為模板時,無法將函數作為參數傳遞給std::thread
。
編譯器:GCC 4.8.2語言:C ++ 11
碼:
//---------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;
}
編譯器錯誤:
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'
兩個問題:
&
並用類名限定函數名。 成員函數名稱與非成員函數名稱的轉換方式不同。 所以在這種情況下,您可能想要
thread t(&test<T>::thr, this, n);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.