mardi 1 décembre 2020

C++11 Passing a function with arguments to a function running in a thread

I am in the process of writing a multithreaded TCP server. I am going to have one thread handle incoming socket connections, and spin off threads to handle the communication on those sockets. However, I want the thread handling socket connections to take as parameters a callback function with supporting parameters, and the compiler is complaining. Here is code to illustrate my problem:

template<class Function, class... Args>
void handleIncomingConnectionRequests(Function&& f, Args... args)
{
    f(args...);
}
    
void callback(int x)
{
    std::cout << x << "\n";
}
    
void main()
{
    std::thread handleIncomingConnectionsThread(handleIncomingConnectionRequests<decltype(callback)>, callback, 5);
    handleIncomingConnectionsThread.join();
}

When I attempt to compile this with clang on Windows, I get a fairly large compilation stack error, but the relevant issue seems to be the following:

error: too few arguments to function call, expected 1, have 0

f(args...);

Why does args appear to have no parameters? I'm clearly passing two arguments to the std::thread constructor. I have clearly done something wrong in the way I am passing the variables in, but I'm not sure how to resolve the issue.

Aucun commentaire:

Enregistrer un commentaire