2016-05-08 92 views
1
void foo(int n){cout << n << '\n';} 

void foo(string s){cout << s << '\n';} 

int main(){ 
    thread t1{foo,9}; 
    thread t2{foo,"nine"}; 
    t1.join(); 
    t2.join(); 
    return 0; 
} 

我得到一個錯誤如何將重載的非成員函數傳遞給線程?

呼叫到std ::螺紋::線程括號內的初始化列表

回答

0

您可以使用static_cast來消除歧義:

static_cast也可用於通過執行函數到指針的轉換來消除函數重載的歧義,如std :: transform(s.begin(),s.end(),s.begin ),static_cast(std :: toupper));

thread t1{static_cast<void(*)(int)>(foo),9}; 
thread t2{static_cast<void(*)(string)>(foo),"nine"}; 
2

沒有匹配的功能需要,以選擇所需的過載功能使用強制。

這裏是做一個工作代碼:

void foo(int n){cout << n << '\n';} 

void foo(string s){cout << s << '\n';} 

int main(){ 
    void (*foo1)(int) = foo; 
    void (*foo2)(string) = foo; 
    thread t1(foo1,9); 
    thread t2(foo2,"nine"); 
    t1.join(); 
    t2.join(); 
    return 0; 
} 
2

我會使用lambda函數的簡單性和可讀性:

thread t1([]{foo(9); }); 
thread t2([]{foo("str");}); 
0

或者你的C風格的直接投它:

thread t1{(void (*)(int))foo,9}; 
thread t2{(void (*)(string))foo,"nine"}; 
+0

除非你需要轉換到私有基,你真的是更好的C++代碼中使用C++風格的轉換。 – StoryTeller

+2

好的,'thread t1 {static_cast (foo),9}; t2 {static_cast (foo),「nine」};',但它更長。 – bipll

相關問題