std::async using an rvalue reference bound to a lambda

后端 未结 1 1609
余生分开走
余生分开走 2021-01-18 01:29

I\'m trying to bind an rvalue reference to a lambda using std::bind, but I have issues when I throw that into a std::async call: (source)



        
相关标签:
1条回答
  • 2021-01-18 01:58

    std::bind is going to make a copy of the std::string argument and pass that to the lambda. But that fails to compile because the lambda requires an rvalue argument, while what bind passes it will be an lvalue. You could get this to work if you get bind to move the argument, but this requires extremely ugly casting for disambiguation (because std::move is an overloaded function).

    auto bound = std::bind(lambda, std::bind(static_cast<std::string&&(*)(std::string&)>(std::move),
                                             std::string{"hello world"}));
    

    Live demo

    You could, of course, write your own version of move that is not overloaded, and avoid that cast.

    The second case works because when bind passes the char const * to the lambda, an rvalue std::string temporary is created implicitly.


    To explain the error message you're seeing, somewhere within the innards of std::async, std::result_of is being invoked to determine the return type of the function call expression. However, because that call expression is invalid due to the reasons explained above, result_of is being SFINAE'd out (this is a C++14 change). Hence the error error: no type named 'type' in 'class std::result_of<...>'.

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