为什么auto不适用于一些lambdas

Mic*_*ker 2 c++ lambda auto c++11

鉴于功能:

void foo(std::function<void(int, std::uint32_t, unsigned int)>& f)
{
    f(1, 2, 4);
}
Run Code Online (Sandbox Code Playgroud)

为什么编译:

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;
};
Run Code Online (Sandbox Code Playgroud)

这无法编译:

auto f =
    [] (int a, std::uint32_t b, unsigned int c) -> void
{
    std::cout << a << b << c << '\n';
    return;
};
Run Code Online (Sandbox Code Playgroud)

有错误:

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)
     ^
Run Code Online (Sandbox Code Playgroud)

Pio*_*cki 13

一个lambda不是std::function.因此,调用该foo函数需要std::function从lambda 构造一个临时对象,并将此临时对象作为参数传递.但是,该foo函数需要一个可修改的左值类型std::function.显然,prvalue临时不能被非const左值引用绑定.采取按值改为:

void foo(std::function<void(int, std::uint32_t, unsigned int)> f)
{
    f(1, 2, 4);
}
Run Code Online (Sandbox Code Playgroud)

  • 通过`const &`捕获也应该正常工作,对吗? (2认同)