没有重载函数"async"的实例与参数列表匹配

3
我将尝试使用异步函数在一个大的csv文件上同时运行多个进程,以避免用户长时间等待,但我遇到了以下错误:
no instance of overloaded function "async" matches the argument list

我在谷歌上搜索了许多内容,但没有找到任何解决方法。由于我对C++编程刚刚入门,所以已经束手无策。非常感谢您的帮助!以下是我的所有代码。

#include "stdafx.h"
#include <cstring>
#include <fstream>
#include <iostream>
#include <string>
#include <algorithm>
#include <future>
using namespace std;

string token;
int lcount = 0;
void countTotal(int &lcount);

void menu()
{
    int menu_choice;

    //Creates the menu
    cout << "Main Menu:\n \n";
    cout << "1. Total number of tweets \n";

    //Waits for the user input
    cout << "\nPlease choose an option: ";
    cin >> menu_choice;

    //If stack to execute the needed functionality for the input
    if (menu_choice == 1) {
        countPrint(lcount);
    } else { //Validation and invalid entry catcher
        cout << "\nPlease enter a valid option\n";
        system("Pause");
        system("cls");
        menu();
    }
}

void countTotal(int &lcount)
{
    ifstream fin;
    fin.open("sampleTweets.csv");

    string line;
    while (getline(fin, line)) {
        ++lcount;
    }

    fin.close();
    return;
}

void countPrint(int &lcount)
{
    cout << "\nThe total amount of tweets in the file is: " << lcount;

    return;
}


int main()
{
    auto r = async(launch::async, countTotal(lcount));
    menu(); //Starts the menu creation

    return 0;
}

2
lcount 是一个全局变量,同时也通过引用在所有函数之间传递。但是现在它并不需要是全局的。此外,您使用了相同的名称来表示全局变量和对该变量的引用。这会造成混淆。如果能够解决这个问题,将会更清晰明了。 - François Andrieux
1个回答

3

这条线

auto r = async(launch::async, countTotal(lcount));

它并不是你所想的那样。它立即调用并评估countTotal(lcount),该函数返回void。因此,代码无效。
查看std::async的文档。它需要一个Callable对象。最简单的方法是使用lambda表达式来生成countTotalCallable并延迟执行:
auto r = async(launch::async, []{ countTotal(lcount); });

如果我使用变量lcount,那么“100”还可以正常工作吗? - Kai Jones
是的,在lambda函数体内部,您可以使用任何int&调用countTotal。 因为100是rvalue,所以实际上不起作用 - 我已经修复了我的答案。 - Vittorio Romeo
或者 auto r = async(launch::async, countTotal, std::ref(lcount)); - WhiZTiM
@Vittorio 如果我们想保留 lcount,这个方法也适用吗?auto r = async(launch::async, [&lcount]{ countTotal(lcount); }); - synchronizer
@synchronizer:lcount是全局变量,我认为不需要被捕获。 - Vittorio Romeo
啊,好的。但它可能不应该是全局的。 - synchronizer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接