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()が関数ではなく、関数として呼び出されたときに関数に変わる関数テンプレートであるためです。

上記は文字列のコピーを逆にして、結果を破棄します。参照によって文字列を渡すには、ラムダ式を。で始まるように変更する必要があります[&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 に答える