[英]How does std::thread store variadic arguments passed through its constructor?
[英]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();
}
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
在哪里:
Function
是线程将调用的可调用对象的类型(无论是函数、lambda、函子等)。Args
是args
可变参数中的类型列表。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.