繁体   English   中英

“std::thread”如何能够确定传递给构造函数的可变参数的数量

[英]How is 'std::thread' is able to determine the number of variadic arguments passed to the constructor

在调用std::thread的构造函数时,您传递一个函数及其所需的参数。 std::thread如何确定要传递给函数的参数总数?

#include <iostream>
#include <thread>

void task(int i, char c, bool b)
{
    return;
}

int main(int argc, char** argv)
{
    std::thread t(task, 10, 'c', true); // these 3 arguments
    t.join();
}

std::thread构造函数是使用可变参数模板实现的

template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );

在哪里:

  • Function是线程将调用的可调用对象的类型(无论是函数、lambda、函子等)。
  • Argsargs可变参数中的类型列表。
  • f是线程将调用的实际可调用对象。
  • args是将传递给f的值列表。

std::thread然后能够使用参数包扩展args转发到f类似于f(args...); . 编译器本身,而不是std::thread ,会将args...扩展为实际值,即: f(arg1, arg2, ..., argN)

所以, std::thread t(task, 10, 'c', true); 将创建一个工作线程,该线程进行类似于f(args...)的调用,该调用将被扩展为task(10, 'c', true)

因此,您传递给std::thread构造函数的参数必须与您传入的f可调用参数的参数匹配,否则代码将无法编译。

std::thread的构造函数的形式为

template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );

如您所见,第一个参数是要运行的函数,其余的是要传递给它的参数。 如果这些不匹配,你会得到某种编译器错误

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM