C ++ 11使用std :: thread运行模板化的类函数

时间:2014-01-31 16:52:46

标签: c++ multithreading c++11

当类定义为模板时,无法将函数作为参数传递给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'

2 个答案:

答案 0 :(得分:3)

您需要完全指定成员函数名称并为非静态成员函数的隐式第一个参数传递参数:

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

请参阅std::thread of a member function

答案 1 :(得分:2)

两个问题:

  • 要获取指向成员函数的指针,您需要使用&并使用类名限定函数名称。成员函数名称不会以与非成员函数名称相同的方式转换为指针。
  • 成员函数需要一个对象来处理。

所以在这种情况下,你可能想要

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