C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c – 可以使用模板函数std :: async大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
std::async是否喜欢使用模板功能我试图将laugh std::reverse作为一个异步任务bu得到编译时错误.

我试图使用更简单的函数(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.end());
    auto resulT_Bar     = std::async(bar,str.end()); // Compile-time error

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

编译错误如下:

@H_694_4@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 ‘<expression error>’ main.cpp:20:62: erreur: no matching function for call to ‘async(<unresolved overloaded function type>,std::basic_String<char>::iterator)’ main.cpp:20:62: note: candidates are: /usr/include/c++/4.6/future:1355:5: note: template<class _Fn,_Args&& ...) main.cpp:20:62: erreur: unable to deduce ‘auto’ from ‘<expression error>’

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

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

解决方法

它可以,但调用有点不同:
auto result_reverse = std::async([&str]() mutable {
        std::reverse(str.begin(),str.end());
    });

这是因为Std :: reverse()不是一个函数,而是一个作为函数调用时变成函数函数模板.

上面的内容反转了一个字符串的副本并抛弃了结果.要通过引用传递字符串,应该将lambda表达式更改为以[& str]()开头.

大佬总结

以上是大佬教程为你收集整理的c – 可以使用模板函数std :: async全部内容,希望文章能够帮你解决c – 可以使用模板函数std :: async所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。