使用std :: async和模板函数

sil*_*ngb 6 c++ algorithm templates c++11 stdasync

我怎样才能或者可以将模板函数传递给异步?

这是代码:

//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;
}
Run Code Online (Sandbox Code Playgroud)

以下是错误消息:

                                                                               ^
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’

Jon*_*ely 10

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

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

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

在lambda的主体内部,编译器为调用执行重载解析std::accumulate,因此它可以解决std::accumulate使用哪个问题.


Pio*_*cki 6

您必须通过显式传递模板参数或使用来消除可能的实例化之间的歧义static_cast,因此:

auto r0 = std::async(std::launch::async
                     , &std::accumulate<decltype(v.begin()), double>
                     , v.begin()
                     , v.end()
                     , 0.0);
Run Code Online (Sandbox Code Playgroud)

要么:

auto r0 = std::async(std::launch::async
       , static_cast<double(*)(decltype(v.begin()), decltype(v.end()), double)>(&std::accumulate)
       , v.begin()
       , v.end()
       , 0.0);
Run Code Online (Sandbox Code Playgroud)