Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rvalue reference binding to an lvalue for std::function types

Why there is no compilation error at (@) in below code? I thought lamb is an lvalue so it will not get bound to an rvalue reference.

using FunctionType = std::function<void()>;
using IntType = int;
struct Foo {
    void bar(FunctionType&&) {}
    void baz(IntType&&) {}
};

Foo foo;
foo.bar([]() {}); //OK
auto lamb = []() {};
foo.bar(lamb); //(@) No compilation error?!
foo.baz(5); //OK
int i = 5;
foo.baz(i); //Error
like image 751
winterlight Avatar asked Feb 06 '23 10:02

winterlight


1 Answers

Since lamb is a lambda and not a std::function, a temporary std::function has to be created and passed to bar(). The temporary binds to the rvalue reference.

Your code is equivalent to this:

auto lamb = [](){};
foo.bar(FunctionType(lamb));

You would get a compile error if you did this instead:

FunctionType func = [](){};
foo.bar(func);
like image 69
Vaughn Cato Avatar answered Feb 07 '23 23:02

Vaughn Cato