mercredi 10 février 2021

Include a class as a function argument in async

I am trying to include an object servreply from an independent class Packet as an argument for a function in std::async. Below is the MWE. This produces an error that states that type deduction of the class has failed. I have tried moving the instantiated object, servreply, I have tried binding and I have tried including a reference to the class type in the function. I have also tried explicitly stating the std::launch::async protocol but no joy. Any ideas?

#include <iostream>
#include <vector>
#include <thread>
#include <future>
#include <stdlib.h>
#include <string>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>

#pragma pack(push, 1)
struct Packet {
    char name[sizeof(std::string)];
    char vec[sizeof(double)];
    char id;
    char cvalue;
    double dvalue;
    int ivalue;
    int timeval;
};
#pragma pack(pop)

struct Client {
    // Socket name
    std::string socket_name;
    // A UNIX socket (types: sun_family, sun_path)
    struct sockaddr_un addr;
    // A file descriptor for the local socket
    int data_socket;

    // Constructor
    Client(std::string insoc) : socket_name(insoc) {};

    // Methods
    // A function to write the packet data to the socket
    int receive_socket(Packet &inpacket); 
};

int Client::receive_socket(Packet &packet) {
    int bytesrec = recv(data_socket, 
            &packet, sizeof(packet), 0);
    if (bytesrec == -1) {
        perror("read_socket");
        exit(EXIT_FAILURE);
    }
    return bytesrec;
}

int main() {
    std::string SOCKET_NAME;
    Client C(SOCKET_NAME);
    Packet servreply;
    //auto rfunc = std::bind(&Client::receive_socket, &C, std::placeholders::_1);
    auto frecv = std::async(&Client::receive_socket, &C, servreply);
    int recvd = frecv.get();
}

Aucun commentaire:

Enregistrer un commentaire