Can std::async be use with template functions

前端 未结 2 1117
忘了有多久
忘了有多久 2021-01-04 09:48

Is std::async supose to work with template function? I\'ve tried to lauch std::reverse as an asynchronous task bu got compile-time error.

I\'ve tried to use simpler

相关标签:
2条回答
  • 2021-01-04 10:24

    std::reverse is not a function but a function template, you can use an specialization of that template (which is a function):

    auto result_reverse = std::async(&std::reverse<std::string::iterator>, str.begin(), str.end());
    
    0 讨论(0)
  • 2021-01-04 10:26

    It can, but the invocation is a bit different:

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

    This is because std::reverse() is not a function, rather a function template that turns into a function when it is invoked as a function.

    The above reverses a copy of the string and throws away the result. To pass the string by reference the lambda expression should be changed to start with [&str]().

    0 讨论(0)
提交回复
热议问题