简体   繁体   English

C ++ 11期货的多态性

[英]Polymorphism with C++11 futures

Say I have two futures, future<int> a and future<char> b . 说我有两个期货, future<int> afuture<char> b Is there any way to put both of these (or pointers to them) into any of the standard containers ( std::{list,vector,...} ? 有没有办法将这两个(或指向它们的指针)放入任何标准容器( std::{list,vector,...}

The problem I intend to solve with this: 我打算解决的问题是:

Setup: I have a thread pool library that allows the user to submit tasks in the form of arbitrary functions w/ arguments as tasks. 设置:我有一个线程池库,该库允许用户以带参量的任意函数的形式提交任务。 The pool executes the function w/ args in a worker thread and the result is communicated to the user by a future<func::result_type> , where func is an std::function<?> . 池在工作线程中执行带有args的函数,结果通过future<func::result_type>传递给用户,其中funcstd::function<?> (? Being a wildcard, b/c it words with any function.) These futures are also the only external way to wait on a task to complete. (?作为通配符,用b / c表示具有任何功能的单词。)这些期货也是等待任务完成的唯一外部方式。 If one only wants to wait until they execute, one must call future::get() and ignore the result. 如果只想等它们执行,就必须调用future::get()并忽略结果。

Problem: I want to provide a way to wait on all the tasks currently in the queue. 问题:我想提供一种等待队列中当前所有任务的方法。 To do this, I need to keep a list of all the futures so I can call get on them. 要做到这一点,我需要把所有的期货的列表,以便我可以打电话get他们。

The library I'm talking about, in case you really need context (280 loc): https://github.com/Tyler-Hardin/thread_pool 我正在谈论的库,以防万一您确实需要上下文(280个位置): https : //github.com/Tyler-Hardin/thread_pool

I don't quite understand why you would need this, but you can use a standard technique - template wrappers with common base class: 我不太明白为什么需要这样做,但是您可以使用标准技术-具有通用基类的模板包装器:

class FutureHolderBase {
public:
    virtual ~FutureHolderBase() = default;
};

template<typename T>
class FutureHolder : public FutureHolderBase {
private:
    std::future<T> m_future;
};

int main() {
    // unfortunately can't use list-initialization here because it supports only copyable types
    std::vector<std::unique_ptr<FutureHolderBase>> v;
    v.push_back(std::make_unique<FutureHolder<int>>());
    v.push_back(std::make_unique<FutureHolder<float>>());
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM