[英]Why does auto not work with some lambdas
Given the function: 鉴于功能:
void foo(std::function<void(int, std::uint32_t, unsigned int)>& f)
{
f(1, 2, 4);
}
Why does this compile: 为什么编译:
std::function<void(int a, std::uint32_t b, unsigned int c)> f =
[] (int a, std::uint32_t b, unsigned int c) -> void
{
std::cout << a << b << c << '\n';
return;
};
And this fails to compile: 这无法编译:
auto f =
[] (int a, std::uint32_t b, unsigned int c) -> void
{
std::cout << a << b << c << '\n';
return;
};
With the error: 有错误:
5: error: no matching function for call to 'foo'
foo(f);
^~~
6: note: candidate function not viable: no known conversion from '(lambda at...:9)' to 'std::function<void (int, std::uint32_t, unsigned int)> &' for 1st argument
void foo(std::function<void(int, std::uint32_t, unsigned int)>& f)
^
A lambda is not a std::function
. lambda不是std::function
。 Thus, calling the foo
function requires construction of a temporary std::function
object from the lambda, and passing this temporary as an argument. 因此,调用foo
函数需要从lambda构造一个临时的std::function
对象,并将此临时值作为参数传递。 However, the foo
function expects a modifiable lvalue of type std::function
. 但是, foo
函数需要一个类型为std::function
的可修改的左值。 Obviously, a prvalue temporary can't be bound by a non-const lvalue reference. 显然,prvalue临时不能被非const左值引用绑定。 Take by value instead: 按值取反:
void foo(std::function<void(int, std::uint32_t, unsigned int)> f)
{
f(1, 2, 4);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.