2016-09-14 48 views
6

我有我的代码中使用std ::线程问题:传类的成员函数到std ::线程

Class Timer 
{ 
... 
public: 
    void Start(bool Asynch = true) 
    { 
     if (IsAlive()) 
     { 
      return; 
     } 
     alive = true; 
     repeat_count = call_number; 
     if (Asynch) 
     { 
      t_thread = std::thread(&ThreadFunc, this); 
     } 
     else 
     { 
      this->ThreadFunc(); 
     } 
    } 
    void Stop() 
    { 
     alive = false; 
     t_thread.join(); 
    } 
... 
} 

我获得以下错误:

error C2276: '&': illegal operation on bound member function expression

t_thread是类的私有STD :: thread实例,ThreadFunc()是返回void的类的私有成员函数;

我想我明白,有2种方式发送成员函数到std :: thread,如果函数是静态的我会使用t_thread = std :: thread(threadfunc);但我不希望ThreadFunc是静态的,并且像这样做会给我错误。

我想我通过创建另一个功能解决了这个问题:

std::thread ThreadReturner() 
{ 
    return std::thread([=] { ThreadFunc(); }); 
} 
... 
t_thread = ThreadReturner(); 

这样,我不明白的错误,但我不明白为什么第一次不工作。

任何帮助表示赞赏。

我的问题看起来像重复,但只有1个区别,在另一个问题的答案中,std :: thread在类声明或实现之外使用,它在main()中,在这种情况下,指定作用域对我来说很重要,但是当std :: thread在类中被调用时不会。这是我看到的唯一区别,也是为什么我做了这个线程,对于可能的重复感到抱歉。

回答

5

您应该指定范围

&Timer::ThreadFunc 
+0

谢谢!这样可行。 – Dragon