C++ 为什么auto不能与一些Lambda一起工作

C++ 为什么auto不能与一些Lambda一起工作,c++,c++11,lambda,auto,C++,C++11,Lambda,Auto,鉴于功能: void foo(std::function<void(int, std::uint32_t, unsigned int)>& f) { f(1, 2, 4); } void foo(标准::函数&f) { f(1,2,4); } 为什么要编译: std::function<void(int a, std::uint32_t b, unsigned int c)> f = [] (int a, std::uint32_t b, un

鉴于功能:

void foo(std::function<void(int, std::uint32_t, unsigned int)>& f)
{
    f(1, 2, 4);
}
void foo(标准::函数&f)
{
f(1,2,4);
}
为什么要编译:

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;
};
std::函数f=
[](整数a,标准::uint32\u t b,无符号整数c)->void
{

std::coutlambda不是
std::function
。因此,调用
foo
函数需要从lambda构造一个临时
std::function
对象,并将该临时对象作为参数传递。然而,
foo
函数需要一个类型为
std::function
的可修改左值。显然prvalue temporary不能由非常量左值引用绑定。请改为按值进行绑定:

void foo(标准::函数f)
{
f(1,2,4);
}

您使用过不同的编译器吗?最好同时使用clang和gcc。可能的重复:通过
常量捕获&
也应该可以,对吗?
auto f =
    [] (int a, std::uint32_t b, unsigned int c) -> void
{
    std::cout << a << b << c << '\n';
    return;
};
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)
     ^
void foo(std::function<void(int, std::uint32_t, unsigned int)> f)
{
    f(1, 2, 4);
}