error with c++ thead

error with c++ thead

本文关键字:thead c++ with error      更新时间:2023-10-16

这是一个小型套接字演示的主文件,我想使用线程来接收服务器回复,但当我尝试创建新线程时:

错误消息:

 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实现只需要一个参数,即必须提供一个null可调用对象或函数,例如通过调用std::bind(receive, client)。在这种情况下,您需要将编译器更新到最新版本。