std线程构造函数使用可变参数线程函数吗?

问题描述 投票:1回答:2

我正在尝试将可变数量的回调函数(都具有相同的签名)传递给线程函数。我想出了以下代码

using namespace std;

void callback(int i)
{
    cout<<"thread "<<i<<" running"<<endl;
}

template<typename ...CallbackType>
void threadProc(int id, CallbackType ...callbackPack)
{
    auto callbacks = {callbackPack...};
    for(auto callback : callbacks)
    {
        callback(id);
    }
}

int main()
{
    thread t(threadProc<void(int)>, 1, callback);
    t.join();
    return 0;
}

此代码无法编译

error: no matching function for call to ‘std::thread::thread(, int, void (&)(int))’
 thread t(threadProc<void(int)>, 1, callback);

如果threadProc()未使用任何参数包,一切正常。是否有正确的方法来启动带有可变线程功能的线程?

c++ multithreading variadic-templates stdthread
2个回答
1
投票

您的代码没有错。这似乎只是GCC中的错误,与线程无关。重现此错误的最小测试用例为:

template <typename... T>
void foo(T...) {}

int main()
{
    auto* pfoo = foo<void(int)>;

    return 0;
}

3
投票

您的第一个参数是函数指针,因此使用

© www.soinside.com 2019 - 2024. All rights reserved.