2016-09-14 46 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