指向模板类的共享指针的向量
我有一个模板类 TaskRunner
,它采用多态类型 Task
,我想创建一个指向它们的共享指针的容器。
class Task {
virtual void run() = 0;
};
class LoudTask : Task {
void run() {
std::cout << "RUNNING!" << std::endl;
}
};
class QuietTask : Task {
void run() {
std::cout << "running!" << std::endl;
}
};
template<typename T> class TaskRunner {
public:
TaskRunner<T>() {
task = std::make_unique<T>();
}
private:
std::unique_ptr<T> task;
};
using Runner = std::shared_ptr<TaskRunner<Task>>;
但是我得到错误:没有匹配的成员函数用于调用'push_back'
:由于
std::vector<Runner> runners;
runners.push_back(std::make_shared<TaskRunner<QuietTask>>());
runners.push_back(std::make_shared<TaskRunner<LoudTask>>());
:
注意:候选函数不可行:没有来自“shared_ptr
”的已知转换到 'const shared_ptr '对于第一个参数
I have a templated class TaskRunner
that takes a polymorphic type Task
and I want to create a container of shared pointers to them.
class Task {
virtual void run() = 0;
};
class LoudTask : Task {
void run() {
std::cout << "RUNNING!" << std::endl;
}
};
class QuietTask : Task {
void run() {
std::cout << "running!" << std::endl;
}
};
template<typename T> class TaskRunner {
public:
TaskRunner<T>() {
task = std::make_unique<T>();
}
private:
std::unique_ptr<T> task;
};
using Runner = std::shared_ptr<TaskRunner<Task>>;
However I get error: no matching member function for call to 'push_back'
with:
std::vector<Runner> runners;
runners.push_back(std::make_shared<TaskRunner<QuietTask>>());
runners.push_back(std::make_shared<TaskRunner<LoudTask>>());
Due to:
note: candidate function not viable: no known conversion from 'shared_ptr<TaskRunner>' to 'const shared_ptr<TaskRunner>' for 1st argument
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实现了iGortAndetnik的建议,它对我有用:
输出:
请注意,TaskRunner不需要是模板;如上所述,它具有双重角色:(1)任务工厂和(2)任务的容器和跑步者。
Paolo的答案很好地将其分开,那里的工厂方面移至主要功能。
Implemented IgorTandetnik's suggestion, and it works for me:
Output:
Note however that TaskRunner doesn't need to be a template; as it is currently implemented above, it has a kind of double role: (1) task factory, and (2) container and runner of tasks.
paolo's answer separates this out nicely, there, the factory aspect is moved to the main function.
如果
TaskRunner
仅应运行从任务
继承的任务,则可以考虑删除它:If
TaskRunner
is supposed to run tasks that inherit fromTask
only, you may consider de-templatizing it:这是另一种实现,消除了对另一个继承层次结构和 vtable 的需要,因为我们已经通过任务层次结构完成了这一点:
This is another implementation that eliminates the need for another inheritance hierarchy and vtable since we already accomplished that with the Task hierarchy: