Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)

auto lambda = [] (std::string&& message) {
    std::cout << message << std::endl;
};
auto bound = std::bind(lambda, std::string{"hello world"});
auto future = std::async(bound); // Compiler error here
future.get()

This issues a compiler error I'm not really sure how to interpret:

error: no type named 'type' in 'class std::result_of(std::basic_string)>&()>'

What's going on here? Interestingly, a slight modification does compile and work as expected. If I change std::string{"hello world"} to a c-string literal, everything works fine: (source)

auto lambda = [] (std::string&& message) {
    std::cout << message << std::endl;
};
auto bound = std::bind(lambda, "hello world");
auto future = std::async(bound);
future.get(); // Prints "hello world" as expected

Why does this work but not the first example?

like image 762
huu Avatar asked May 06 '15 18:05

huu


1 Answers

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<...>'.

like image 118
Praetorian Avatar answered Oct 19 '22 22:10

Praetorian