【问题标题】:Why does auto not work with some lambdas为什么 auto 不适用于某些 lambda
【发布时间】:2015-12-10 04:51:15
【问题描述】:

给定函数:

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

【问题讨论】:

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


【解决方案1】:

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

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

【讨论】:

  • const&amp; 捕获应该也能正常工作,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-29
  • 2013-08-12
  • 1970-01-01
  • 1970-01-01
  • 2012-10-28
  • 2020-08-05
  • 1970-01-01
相关资源
最近更新 更多