gpt4 book ai didi

c++ - 'std::thread'如何确定传递给构造函数的可变参数的数量

转载 作者:行者123 更新时间:2023-12-03 06:57:48 24 4
gpt4 key购买 nike

当调用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 constructor是使用variadic template实现的:

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的参数匹配,否则代码将无法编译。

    关于c++ - 'std::thread'如何确定传递给构造函数的可变参数的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64235651/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com