C++ - 期货向量

C++ - vector of futures

本文关键字:向量 C++      更新时间:2023-10-16

以下代码无法编译:

#include <iostream>
#include <future>
#include <vector>
class Calculator {
public:
    static int add(int a, int b)
    {
        return a + b;
    }
};
int main(int argc, char* argv[]) {
    std::vector<std::future<int>*> futures;
    for(auto i = 0; i < 4; i++) {
        auto future = new std::async(&Calculator::add, 1, 3);
        futures.push_back(future);
    }
    for(auto i = 0; i < 4; i++) {
        std::cout << futures[i]->get() << std::endl;
        delete futures[i];
    }
    return 0;
}

我收到以下错误:

error: no type named 'async' in namespace 'std'

如何在期货向量上存储和调用 get((?

更新:

我正在使用C++ 11和一个没有矢量逻辑的异步示例工作正常。

由于任何使用裸newdelete调用的代码(顺便说一下,这是一种很好的开发态度(,我重写了它以使用更"现代"的C++习语。

我不完全确定为什么你认为你需要存储指向期货的指针,这似乎不必要地使事情复杂化。无论如何,该代码片段new std::async()g++带来了问题,我相信这就是您的错误no type named 'async' in namespace 'std'的原因。

从技术上讲,这是正确的,std中没有类型async,因为async是一个函数而不是一个类型。

修改后的代码如下:

#include <iostream>
#include <future>
#include <vector>
class Calculator {
public:
    static int add(int a, int b) { return a + b; }
};
int main() {
    std::vector<std::future<int>> futures;
    for(auto i = 0; i < 4; i++)
        futures.push_back(std::async(&Calculator::add, i, 3));
    for(auto i = 0; i < 4; i++)
        std::cout << futures[i].get() << std::endl;
    return 0;
}

这编译和运行得很好,给出了我希望看到的结果:

pax> g++ -Wall -Wextra -pthread -std=c++11 -o testprog testprog.cpp
pax> ./testprog
3
4
5
6