'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's constructor 的形式为

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

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

std::thread constructor is implemented using a variadic template:

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

其中:

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

std::thread 然后能够使用 参数包扩展 similar[=55] 将 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 可调用对象的参数相匹配,否则代码将无法编译。