使用std :: async和模板函数

时间:2014-09-12 18:49:32

标签: c++ algorithm c++11 templates 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;
}

以下是错误消息:

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

2 个答案:

答案 0 :(得分:9)

问题是要将第二个参数传递给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

答案 1 :(得分:5)

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

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

或:

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);