c++ - 将 std::async 与模板函数一起使用

标签 c++ algorithm c++11 templates stdasync

我如何,或者,我可以将模板函数传递给 async?

代码如下:

//main.cpp
#include <future>
#include <vector>
#include <iostream>
#include <numeric>

int
main
    ()
{      
    std::vector<double> v(16,1);

    auto r0 =  std::async(std::launch::async,std::accumulate,v.begin(),v.end(),double(0.0));

    std::cout << r0.get() << std::endl;
    return 0;
}

错误信息如下:

                                                                               ^
a.cpp:13:88: note: candidates are:
In file included from a.cpp:1:0:
/usr/include/c++/4.8/future:1523:5: note: template std::future::type> std::async(std::launch, _Fn&&, _Args&& ...)
     async(launch __policy, _Fn&& __fn, _Args&&... __args)
     ^
/usr/include/c++/4.8/future:1523:5: note:   template argument deduction/substitution failed:
a.cpp:13:88: note:   couldn't deduce template parameter ‘_Fn’
   auto r0 = std::async(std::launch::async,std::accumulate,v.begin(),v.end(),double(0.0));
                                                                                        ^
In file included from a.cpp:1:0:
/usr/include/c++/4.8/future:1543:5: note: template std::future::type> std::async(_Fn&&, _Args&& ...)
     async(_Fn&& __fn, _Args&&... __args)
     ^
/usr/include/c++/4.8/future:1543:5: note:   template argument deduction/substitution failed:
/usr/include/c++/4.8/future: In substitution of ‘template std::future::type> std::async(_Fn&&, _Args&& ...) [with _Fn = std::launch; _Args = {}]’:
a.cpp:13:88:   required from here
/usr/include/c++/4.8/future:1543:5: error: no type named ‘type’ in ‘class std::result_of’

最佳答案

问题是要将第二个参数传递给 std::async 编译器必须将表达式 &std::accumulate 转换为函数指针,但它不会'知道你想要的函数模板的哪个特化。对人类来说,很明显您想要可以使用 async 的剩余参数调用的那个,但编译器不知道这一点,因此必须分别评估每个参数。

正如 PiotrS. 的回答所说,您可以使用显式模板参数列表或使用强制转换告诉编译器您想要哪个 std::accumulate,或者您也可以只使用 lambda表达式代替:

std::async(std::launch::async,[&] { return std::accumulate(v.begin(), v.end(), 0.0); });

在 lambda 的主体内,编译器对 std::accumulate 的调用执行重载解析,因此它计算出使用哪个 std::accumulate

关于c++ - 将 std::async 与模板函数一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25814879/

相关文章:

c++ - Eclipse CDT:无法解析类型 std::string

c++ - 如何加快MFC中旋转文本的输出

c++ - 没有上下文类型信息的重载函数 |无法根据转换为类型 'swap' 解析重载函数 'int'

C++98/03 std::is_constructible 实现

c++ - 指针算术编译失败,gcc 说类型转换无效

c++ - 从中心而不是从左、中间旋转

algorithm - 在相同位置合并重叠点的快速方法

algorithm - 解决一系列问题所需的最少天数

c++ - 如何检查一个类是否继承了另一个类?

c++ - 没有用于初始化 std::lock_guard<std::mutex> 的匹配构造函数