鉴于功能:
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)
^
答案 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);
}