C++ - 期货向量
C++ - vector of futures
以下代码无法编译:
#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,没有矢量逻辑的异步示例工作正常。
深深地怀疑任何使用裸new
或delete
调用的代码(顺便说一下,这是一种良好的开发态度),我重写了它使用更多 'modern' C++ 习语。
我不是完全 确定为什么你认为你需要存储 指针 到期货,这似乎不必要地使事情复杂化。无论如何,片段 new std::async()
给 g++
带来了问题,我相信这就是你的错误 no type named 'async' in namespace 'std'
.
的原因
从技术上讲,这是正确的,std
中没有 type 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
以下代码无法编译:
#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,没有矢量逻辑的异步示例工作正常。
深深地怀疑任何使用裸new
或delete
调用的代码(顺便说一下,这是一种良好的开发态度),我重写了它使用更多 'modern' C++ 习语。
我不是完全 确定为什么你认为你需要存储 指针 到期货,这似乎不必要地使事情复杂化。无论如何,片段 new std::async()
给 g++
带来了问题,我相信这就是你的错误 no type named 'async' in namespace 'std'
.
从技术上讲,这是正确的,std
中没有 type 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