2016-05-08 49 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

相关问题