12

是否std::async可以使用模板功能?我尝试将std::reverse其作为异步任务启动,但出现编译时错误。

我尝试使用更简单的函数(foo 和 bar),发现只有非模板函数在工作。

#include <algorithm>
#include <future>
#include <string>

void foo(std::string::iterator first, std::string::iterator last)
{
}

template<class BidirectionalIterator>
void bar(BidirectionalIterator first, BidirectionalIterator last)
{
}

int main()
{
    std::string str = "Lorem ipsum, dolor sit amet";

    auto result_reverse = std::async(std::reverse, str.begin(), str.end()); // Compile-time error
    auto result_foo     = std::async(foo, str.begin(), str.end());
    auto result_bar     = std::async(bar, str.begin(), str.end()); // Compile-time error

    result_reverse.get();
    result_foo.get();
    result_bar.get();
}

编译器错误如下:

main.cpp: In function ‘int main()’:
main.cpp:18:71: erreur: no matching function for call to ‘async(<unresolved overloaded function type>, std::basic_string<char>::iterator, std::basic_string<char>::iterator)’
main.cpp:18:71: note: candidates are:
/usr/include/c++/4.6/future:1355:5: note: template<class _Fn, class ... _Args> std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(std::launch, _Fn&&, _Args&& ...)
/usr/include/c++/4.6/future:1378:5: note: template<class _Fn, class ... _Args> typename std::__async_sfinae_helper<typename std::decay<_Functor>::type, _Fn, _Args ...>::type std::async(_Fn&&, _Args&& ...)
main.cpp:18:71: erreur: unable to deduce ‘auto’ from ‘&lt;expression error>’
main.cpp:20:62: erreur: no matching function for call to ‘async(<unresolved overloaded function type>, std::basic_string<char>::iterator, std::basic_string<char>::iterator)’
main.cpp:20:62: note: candidates are:
/usr/include/c++/4.6/future:1355:5: note: template<class _Fn, class ... _Args> std::future<typename std::result_of<_Functor(_ArgTypes ...)>::type> std::async(std::launch, _Fn&&, _Args&& ...)
/usr/include/c++/4.6/future:1378:5: note: template<class _Fn, class ... _Args> typename std::__async_sfinae_helper<typename std::decay<_Functor>::type, _Fn, _Args ...>::type std::async(_Fn&&, _Args&& ...)
main.cpp:20:62: erreur: unable to deduce ‘auto’ from ‘&lt;expression error>’

但是,当我手动指定模板实例时它通过了,例如std::async(std::reverse<std::string::iterator>, str.begin(), str.end()).

这是编译器错误(GCC 4.6.3)还是定义明确的行为?

4

2 回答 2

14

它可以,但调用有点不同:

auto result_reverse = std::async([&str]() {
        std::reverse(str.begin(), str.end());
    });

这是因为std::reverse()不是函数,而是当作为函数调用时变成函数的函数模板。

以上反转字符串的副本并丢弃结果。要通过引用传递字符串,应将 lambda 表达式更改为以[&str]().

于 2012-05-16T14:40:23.520 回答
8

std::reverse不是函数而是函数模板,您可以使用该模板的特化(这是一个函数):

auto result_reverse = std::async(&std::reverse<std::string::iterator>, str.begin(), str.end());
于 2012-05-16T16:43:14.547 回答