为什么auto不适用于一些lambdas

时间:2015-09-14 08:43:01

标签: c++ c++11 lambda auto

鉴于功能:

void foo(std::function<void(int, std::uint32_t, unsigned int)>& 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;
};

这无法编译:

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)
     ^

1 个答案:

答案 0 :(得分:13)

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

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