错误C2064:term不评估为带有1个参数的函数 - 关于线程的东西

时间:2017-05-20 23:10:08

标签: c++ multithreading client-server

我收到了这个错误:

error C2064: term does not evaluate to a function taking 1 arguments

我不知道为什么,但我发现它的一些关于线程(如果我注释掉它编译的线程的线条)。 问题在于:

thread t(&TriviaServer::clientHandler, this->_socket);

thread t(&TriviaServer::clientHandler, client_socket);

来自函数serve()和acceptClient。

我的代码:

#include "TriviaServer.h"

#define PORT 8820
#define IFACE 0


TriviaServer::TriviaServer()
{
    this->_db = DataBase();
    this->_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (this->_socket == INVALID_SOCKET)
        throw exception(__FUNCTION__ " - socket");
}

TriviaServer::~TriviaServer()
{
    for (unsigned int i = 0; i < this->_connectedUsers.size(); i++)
        delete this->_connectedUsers[i];
    this->_connectedUsers.clear();
    for (unsigned int i = 0; i < this->_roomList.size(); i++)
        delete this->_roomList[i];
    this->_roomList.clear();
    TRACE(__FUNCTION__ " closing accepting socket");
    try
    {
        closesocket(this->_socket);
    }
    catch (exception e)
    {
        cout << e.what() << endl;
    }
    catch (...) {}
}

void TriviaServer::serve()
{
    bindAndListen();

    thread t(&TriviaServer::clientHandler, this->_socket);
    t.detach();

    while (true)
    {
        TRACE("accepting client...");
        acceptClient();
    }
}

void TriviaServer::bindAndListen()
{
    struct sockaddr_in sockAddr = { 0 };
    sockAddr.sin_port = PORT;
    sockAddr.sin_family = AF_INET;
    sockAddr.sin_addr.s_addr = IFACE;

    if (::bind(this->_socket, (struct sockaddr*)&sockAddr, sizeof(sockAddr)) == SOCKET_ERROR)
        throw exception(__FUNCTION__ " - bind");
    TRACE("binded");

    if (::listen(this->_socket, SOMAXCONN) == SOCKET_ERROR)
        throw exception(__FUNCTION__ " - listen");
    TRACE("listening...");
}

void TriviaServer::acceptClient()
{
    SOCKET client_socket = accept(this->_socket, NULL, NULL);
    if (client_socket == INVALID_SOCKET)
        throw exception(__FUNCTION__);

    TRACE("Client accepted !");

    thread t(&TriviaServer::clientHandler, client_socket);
    t.detach();
}

void TriviaServer::clientHandler(SOCKET)
{
    //TODO
}

是否有人知道原因以及如何解决?

1 个答案:

答案 0 :(得分:1)

thread t(&TriviaServer::clientHandler, this->_socket);

由于&TriviaServer::clientHandler定义为:

TriviaServer::clientHandler(SOCKET);

通过函数指针 &TriviaServer::clientHandler传递给调用的第一个参数是this类型的隐式TriviaServer参数,或指向TriviaServer的对象。您需要在函数声明采用的任何其他参数之前传递它。所以你想做:

thread t(&TriviaServer::clientHandler, this, this->_socket);