std::thread 中的参数。如何运作?

Arguments in std::thread. How works?

使用示例std::thread构造函数:

#include <thread>
using namespace std;

void a_function(){}
void a_function2(int a){}
void a_function3(int a,int b){}
void a_function4(int &a){}

class a_class
{
public:
    void a_function5(int a){}
};

int main()
{
    a_class aux;
    int a = 2;

    thread t(a_function);
    thread t2(a_function2,2);
    thread t3(a_function3,2,3);
    thread t4(a_function4,ref(a));
    thread t5(&a_class::a_function5,&aux,2);

    t.join();
    t2.join();
    t3.join();
    t4.join();
    t5.join();
}

构造函数如何知道参数的数量?构造函数如何调用一种未知类型的函数?我怎么能实现这样的东西?例如,std::thread

的一个包装器
class wrapper_thread
{
   thread t;

   public:

         wrapper_thread() //what arguments here?
         : t() //What arguments here?
         {}
}

您要查找的是 parameter pack 运算符。使用它可以编写一个接受可变数量参数的函数。它可以用这些参数做一些事情,比如将它们转发给另一个函数。

请记住,由于模板是在编译时实例化的,因此在调用站点必须知道参数的数量及其类型。

实现包装器线程 class' 构造函数的简单方法可能是:

template <typename ... Args> // this ctor has variadic template arguments
wrapper_thread(Args& ... args) // pack references to arguments into 'args' 
     : t(args...) //unpack arguments, pass them as parameters to the ctor of std::thread

一旦你明白了,你可以看看std::forward() to do perfect forwarding. Andrei Alexandrescu gives a great talk on variadic templates. You can find it here: http://channel9.msdn.com/Events/GoingNative/GoingNative-2012/Variadic-Templates-are-Funadic