【问题标题】:async returns future of void type instead of expected typeasync 返回 void 类型而不是预期类型的​​ future
【发布时间】:2016-03-03 00:55:12
【问题描述】:

我正在学习 C++ 的期货和异步编程。我有以下代码基于 Stroustrup 的 C++ 参考第 42 章中的代码。 GCC 和 Microsoft 编译器都抱怨在对 push_back 的调用中没有从 future<void>future<InputIterator> 的转换。为什么对 async 的调用会返回 future<void> 而不是 future<std::iterator> 我期望从 std::find 得到的?

template<typename T, typename InputIter>
InputIter p_find(InputIter first, InputIter last, const T& value, const int grain)
{
    std::vector<std::future<InputIter>> results;
    while (first != last)
    {
        results.push_back(std::async([=]() mutable {std::find(first, first + grain, value); }));
        first += grain;
    }
    //blah blah

【问题讨论】:

    标签: c++ c++11


    【解决方案1】:

    你的 lambda 什么都不返回(即void),所以async() 的结果是std::future&lt;void&gt;。你想要的大概是

    results.push_back(std::async([=]() mutable {return std::find(first, first + grain, value); }));
    //                                          ^^^^^^
    

    【讨论】:

    • 谢谢。做到了。现在在 MSVC 2013 中编译。
    猜你喜欢
    • 1970-01-01
    • 2020-01-14
    • 2020-06-14
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 1970-01-01
    • 1970-01-01
    • 2021-10-18
    相关资源
    最近更新 更多