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
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With