gpt4 book ai didi

c++ - 为什么 auto 不适用于某些 lambda

转载 作者:太空狗 更新时间:2023-10-29 23:30:03 26 4
gpt4 key购买 nike

给定函数:

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 的可修改左值。显然,临时纯右值不能被非常量左值引用绑定(bind)。取而代之的是:

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

关于c++ - 为什么 auto 不适用于某些 lambda,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32560523/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com