为什么 auto 不适用于某些 lambda
Why does auto not work with some lambdas
给定函数:
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)
^
lambda 不是 std::function
。因此,调用 foo
函数需要从 lambda 构造一个临时的 std::function
对象,并将这个临时对象作为参数传递。但是,foo
函数需要一个类型为 std::function
的可修改左值。显然,临时纯右值不能被非常量左值引用绑定。取值代替:
void foo(std::function<void(int, std::uint32_t, unsigned int)> f)
{
f(1, 2, 4);
}
给定函数:
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)
^
lambda 不是 std::function
。因此,调用 foo
函数需要从 lambda 构造一个临时的 std::function
对象,并将这个临时对象作为参数传递。但是,foo
函数需要一个类型为 std::function
的可修改左值。显然,临时纯右值不能被非常量左值引用绑定。取值代替:
void foo(std::function<void(int, std::uint32_t, unsigned int)> f)
{
f(1, 2, 4);
}