Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
678 views
in Technique[技术] by (71.8m points)

c++ - 'invoke': no matching overloaded function found

Trying to make an organized "announcement" message-board with multi-threading. One thread reads messages and calls the other thread to send said messages to connected users.

I'm not entirely sure why the std::thread constructor fails to compile. I've tried ref()ing everything, didn't work. I've tried ref()ing only the stuff that needs to be referenced, didn't work.

#include <queue>
#include <string>
#include <set>
#include <fstream>
#include <thread>

namespace MenuVariables {
    std::set<std::string> usernames;
    std::queue<std::string> messages;
}

namespace MessageHandler {
    void readMessages(std::queue<std::string>& messages, std::string inputFile);
    void sendMessages(std::queue<std::string>& messages, std::set<std::string>& users, std::ofstream outputFile);
}

int main() {
    std::string inputFile = "data.txt";
    std::ofstream outputFile("output.txt");
    
    std::thread readThread(MessageHandler::readMessages, std::ref(MenuVariables::messages), inputFile);
    std::thread sendThread(MessageHandler::sendMessages, std::ref(MenuVariables::messages), std::ref(MenuVariables::usernames), outputFile);
    readThread.detach();
    sendThread.detach();
    return 0;
}

What shall I do? The errors are: Errors

question from:https://stackoverflow.com/questions/65863428/invoke-no-matching-overloaded-function-found

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

sendMessages takes a std::ofstream by value, as std::ofstream is not copyable, even without std::thread you can only call it with a temporary or r value.

For example this won't compile:

MessageHandler::sendMessages(MenuVariables::messages, MenuVariables::usernames, outputFile);

but either of these will:

MessageHandler::sendMessages(MenuVariables::messages, MenuVariables::usernames, std::move(outputFile));
MessageHandler::sendMessages(MenuVariables::messages, MenuVariables::usernames, ofstream("output.txt"));

You therefore have the same options to make your std::thread constructor work:

thread sendThread(MessageHandler::sendMessages, ref(MenuVariables::messages), ref(MenuVariables::usernames), std::move(outputFile));
thread sendThread(MessageHandler::sendMessages, ref(MenuVariables::messages), ref(MenuVariables::usernames), ofstream("output.txt"));

Alternatively change sendMessages to take outputFile by reference:

void sendMessages(queue<string>& messages, set<string>& users, ofstream& outputFile);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...