【问题标题】:How to pass overloaded nonmember functions to threads?如何将重载的非成员函数传递给线程?
【发布时间】:2016-05-08 09:56:24
【问题描述】:
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::thread::thread 大括号封闭的初始化列表

【问题讨论】:

    标签: c++ multithreading


    【解决方案1】:

    为了简单和可读性,我会使用 lambda 函数:

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

    【讨论】:

      【解决方案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;
      }
      

      【讨论】:

        【解决方案3】:

        您可以使用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"};
        

        【讨论】:

          【解决方案4】:

          或者你可以直接用 C 风格转换它:

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

          【讨论】:

          • 除非您需要强制转换为私有库,否则您确实最好在 c++ 代码中使用 c++ 风格的强制转换。
          • 好的,thread t1{static_cast&lt;void (*)(int)&gt;(foo),9}; t2{static_cast&lt;void (*)(string)&gt;(foo),"nine"};,但它更长。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-01-26
          • 2016-12-12
          • 2016-02-20
          • 2018-09-18
          • 1970-01-01
          相关资源
          最近更新 更多