这是一个小型套接字演示的主文件,我想使用线程来接收服务器回复,但是当我尝试创建新线程时:
错误信息:
error: no matching constructor for initialization of 'std::thread'
代码:
#include <iostream>
#include <thread>
#include "client_socket.h"
#include "socket_exception.h"
void receive(ClientSocket client)
{
std::string reply;
while (true) {
client >> reply;
std::cout << "We received this response from the server:" << std::endl;
std::cout << "\"" << reply << "\"" << std::endl;
}
}
int main(int argc, const char* argv[])
{
try {
ClientSocket client("127.0.0.1", 30000);
std::string sendBuf;
std::thread receiver(receive, client);
receiver.join();
while (true) {
std::cout << "Enter string send to server:" << std::endl;
std::cin >> sendBuf;
if (sendBuf.compare("quit") == 0) {
break;
}
try {
client << sendBuf;
} catch (SocketException&) {}
}
} catch (SocketException& e) {
std::cout << "Exception was caught:" << e.description() << std::endl;
}
return 0;
}
使用的线程有问题吗?谢谢
最佳答案
据我所知,您有一个有效的线程构造函数调用,因为有一个用于 1..N 任意参数的模板构造函数。错误的参数会导致该构造函数内部出现编译错误,而不是您收到的错误消息。其他可能的错误,例如未能将 receive
识别为对您之前定义的函数的引用,也会导致不同的错误消息。您的 std::thread
实现中似乎没有模板化的多参数构造函数。
IIRC 几年前,早期的 std::thread
实现只接受一个参数,即你必须提供一个 nullary 可调用对象或函数,例如通过调用 std::bind(receive, client)
。在这种情况下,您需要将编译器更新到更新的版本。
关于c++ - c++ thead错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26754930/