gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:07:12 26 4
gpt4 key购买 nike

我如何,或者,我可以将模板函数传递给 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com