簡體   English   中英

C ++ 11使用std :: thread運行模板化類函數

[英]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);

參見成員函數的std::thread

兩個問題:

  • 要獲得指向成員函數的指針,您需要使用&並用類名限定函數名。 成員函數名稱與非成員函數名稱的轉換方式不同。
  • 成員函數需要作用的對象。

所以在這種情況下,您可能想要

thread t(&test<T>::thr, this, n);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM