我的代码包含2个文件:main.cpp
和utils.hpp
。这些文件的内容如下:
utils.hpp
#ifndef UTILITY_HPP
#define UTILITY_HPP
#include <iostream>
#include <thread>
#include <future>
#include <functional>
#include <chrono>
using std::chrono::milliseconds;
class CallableStoppableTask {
std::promise<void> exit_signal;
std::future<void> future_obj;
public:
CallableStoppableTask() : future_obj(exit_signal.get_future()) {}
CallableStoppableTask(const CallableStoppableTask&) = delete;
CallableStoppableTask& operator=(const CallableStoppableTask&) = delete;
virtual void run() = 0;
void operator()() { run(); }
bool is_stop_requested(int timeout_milliseconds = 0) const {
return (future_obj.wait_for(milliseconds(timeout_milliseconds)) == std::future_status::ready);
}
void request_stop() { exit_signal.set_value(); }
};
struct Car {
int model;
int price;
explicit Car(const int& arg_model = -1, const int& arg_price = -1)
: model(arg_model), price(arg_price) {}
};
class CallableSampleTask : public CallableStoppableTask {
CallableSampleTask(const CallableSampleTask&) = delete;
CallableSampleTask& operator=(const CallableSampleTask&) = delete;
void run() override {
std::cout << "Running Some Car Sample Task.. " << std::endl;
}
public:
CallableSampleTask(const Car& arg_car = Car()) {}
};
#endif
为了实现可以中断的任务,我们继承了CallableStoppableTask
for,例如CallableSampleTask
。
的内容main.cpp
是:
#include "utils.hpp"
#include <iostream>
#include <array>
#include <future>
#include <memory>
#define NUM_TASK 5
static std::array<std::unique_ptr<CallableSampleTask>, NUM_TASK> ar_uptr_task;
int main() {
std::unique_ptr<CallableSampleTask> f = std::move(std::make_unique<CallableSampleTask>());
(*f.get())(); // COMPILE TIME ERROR: what is the error in this?
ar_uptr_task.fill(std::move(std::make_unique<CallableSampleTask>()));
for (int i = 0; i < NUM_TASK; i++) {
// I want to do something like this. COMPILE TIME ERROR
auto discard_ret = std::async(std::launch::async, (*ar_uptr_task[i].get()));
}
std::cout << "Hello, World!" << std::endl;
return 0;
}
上面引发了一个非常大的COMPILE TIME ERROR。我已经注释了main.cpp
引发错误的文件中的行。
我正在使用以下命令进行编译:
g++ -std=c++17 -pthread main.cpp
知道我要去哪里和哪里出问题了吗?
PS:如果我缺少某些知识,请以出色的C ++概念启发我。
我无法发布错误,因为它超出了stackoverflow的限制。这是github链接:https : //github.com/KishoreKaushal/CallableObjects
这条线很好
(*f.get())(); // COMPILE TIME ERROR: what is the error in this?
但较短的版本
(*f)();
更好。
ar_uptr_task.fill(std::move(std::make_unique<CallableSampleTask>()));
没有任何意义。fill
将源作为const对象,您如何在const源对象上应用移动操作[也想将源对象移动N次,但首先移动操作会使源对象处于空状态]?
可以替换为:
for (int i = 0; i < 5; ++i)
ar_uptr_task[i] = std::make_unique<CallableSampleTask>();
如果要传递函子async
起作用,请reference_wrapper
使用ref
以下命令将其包装起来:
for (int i = 0; i < NUM_TASK; i++) {
auto discard_ret = std::async(std::launch::async, std::ref(*ar_uptr_task[i]));
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句