[英]How is 'std::thread' is able to determine the number of variadic arguments passed to the constructor
When calling the constructor of std::thread
you pass a function and its desired arguments.在调用
std::thread
的构造函数时,您传递一个函数及其所需的参数。 How does std::thread
determine the total number of arguments meant to be passed to the function? 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();
}
The std::thread
constructor is implemented using a variadic template :std::thread
构造函数是使用可变参数模板实现的:
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
Where:在哪里:
Function
is the type of callable object that will be invoked by the thread (whether that be a function, a lambda, a functor, etc). Function
是线程将调用的可调用对象的类型(无论是函数、lambda、函子等)。Args
is the list of types in the args
variadic parameter. Args
是args
可变参数中的类型列表。f
is the actual callable object that the thread will invoke. f
是线程将调用的实际可调用对象。args
is the list of values that will be passed to f
. args
是将传递给f
的值列表。 std::thread
is then able to forward args
to f
using parameter pack expansion , similar to f(args...);
std::thread
然后能够使用参数包扩展将args
转发到f
,类似于f(args...);
. . The compiler itself, not
std::thread
, will expand args...
to the actual values, ie: f(arg1, arg2, ..., argN)
.编译器本身,而不是
std::thread
,会将args...
扩展为实际值,即: f(arg1, arg2, ..., argN)
。
So, std::thread t(task, 10, 'c', true);
所以,
std::thread t(task, 10, 'c', true);
will create a worker thread that make a call similar to to f(args...)
, which will have been expanded to task(10, 'c', true)
.将创建一个工作线程,该线程进行类似于
f(args...)
的调用,该调用将被扩展为task(10, 'c', true)
。
Thus, the arguments you pass to the std::thread
constructor must match the arguments of the f
callable you pass in, otherwise the code fails to compile.因此,您传递给
std::thread
构造函数的参数必须与您传入的f
可调用参数的参数匹配,否则代码将无法编译。
std::thread
's constructor has the form ofstd::thread
的构造函数的形式为
template< class Function, class... Args >
explicit thread( Function&& f, Args&&... args );
As you can see, the first argument is the function to run, and the rest are the arguments to be passed to it.如您所见,第一个参数是要运行的函数,其余的是要传递给它的参数。 If those don't match, you get some sort of compiler error
如果这些不匹配,你会得到某种编译器错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.