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

标签 c++

我正在尝试使用异步函数一次在大型 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;
}

最佳答案

线

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

并没有按照您的想法行事。它立即调用并计算 countTotal(lcount),它返回 void。因此该代码无效。


查看documentation for std::async .它需要一个 Callable目的。为 countTotal 生成 Callable 并延迟执行的最简单方法是使用 lambda:

auto r = async(launch::async, []{ countTotal(lcount); });

关于c++ - 没有重载函数的实例 "async"匹配参数列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44286345/

相关文章:

c++ - Qt - 如何从线程创建 QFuture

c++ - 试图通过 system() 运行字符串命令

c++ - 具有成员函数和携带参数的构造函数的多线程

c++ - 避免/检测对导出文件的操纵

c++ - 位于不同命名空间时运算符的重载不明确

c++ - 位图正在拉伸(stretch)而不是平铺

c++ - std::make_unique<T> 与重置(新 T)

c++ - 为什么我的互斥量没有在我的其他线程锁定它之前锁定它?

c++ - 删除目录中的所有文件

c++ - 派生类中的方法多于基类