简体   繁体   English

为什么auto不适用于一些lambdas

[英]Why does auto not work with some lambdas

Given the function: 鉴于功能:

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

Why does this compile: 为什么编译:

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;
};

And this fails to compile: 这无法编译:

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

With the error: 有错误:

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

A lambda is not a std::function . lambda不是std::function Thus, calling the foo function requires construction of a temporary std::function object from the lambda, and passing this temporary as an argument. 因此,调用foo函数需要从lambda构造一个临时的std::function对象,并将此临时值作为参数传递。 However, the foo function expects a modifiable lvalue of type std::function . 但是, foo函数需要一个类型为std::function的可修改的左值。 Obviously, a prvalue temporary can't be bound by a non-const lvalue reference. 显然,prvalue临时不能被非const左值引用绑定。 Take by value instead: 按值取反:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么在三元运算符的分支之间返回lambda对于某些lambda起作用? - Why does returning lambdas between branches of ternary operator work for some lambdas? 为什么std :: result_of不适用于lambdas? - Why does std::result_of not work with lambdas? C ++ Lambdas,捕获,智能Ptrs和堆栈:为什么这有效? - C++ Lambdas, Capturing, Smart Ptrs, and the Stack: Why Does this Work? 为什么“自动”在这种情况下不起作用? - Why does “auto” not work in this case? ADL是否与命名的lambdas一起使用? - Does ADL work with named lambdas? 为什么原子不能与自动变量一起使用 - why atomic does not work with auto varaible 为什么 std::is_invocable 不能与模板化的 operator() 一起使用,它的返回类型是自动推导的(例如通用 lambdas) - Why doesn't std::is_invocable work with templated operator() which return type is auto-deduced (eg. generic lambdas) 为什么构造函数在某些情况下不起作用? - Why constructor does not work in some cases? 为什么有些代码可以在 HackerRank 中运行,而在 Xcode 中不起作用 - Why does some code work HackerRank but not Xcode 模板功能:是否有语法可以接受任何参数类型,就像lambda的&#39;auto&#39;一样? - Template function: is there a syntax for accepting any argument type, as 'auto' does for lambdas?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM