使用 std::function 调用函数作为带有 lambda 的参数

Call a function with std::function as argument with a lambda

本文关键字:lambda 参数 std function 调用 函数 使用      更新时间:2023-10-16

我从这里得到的问题的基础: 无法从 lambda 函数推导出模板参数 std::function 这个线程中的问题是: 为什么这段代码不能将lambda传递给函数:

#include <iostream>
#include <functional>
template <typename T>
void call(std::function<void(T)> f, T v)
{
f(v);
}
int main(int argc, char const *argv[])
{
auto foo = [](int i) {
std::cout << i << std::endl;
};
call(foo, 1);
return 0;
}

这个线程中的答案是,因为 lambda 不是std::function.但是为什么要编译这段代码:

#include <iostream>
#include <functional>
template <typename T>
void call(std::function<void(T)> f, T v)
{
f(v);
}
int main(int argc, char const *argv[])
{
auto foo = [](int i) {
std::cout << i << std::endl;
};
call({foo}, 1); // changed foo to {foo}
return 0;
}

正如链接答案中所写,第一个版本不编译,因为第一个参数的模板参数推导失败; lambda 从来都不是std::function<void(T)>

第二个版本编译,因为通过编写{foo}std::function<void(T)>成为一个非推导的上下文。因此,对于第一个参数,演绎不能再失败,因为它甚至没有尝试过。因此,仅从第二个参数推断出Tint,并且调用成功,因为 lambda 可转换为std::function<void(int)>

从 [温度扣除类型]:

非推导上下文是:

  • 一个函数参数,其关联参数是初始值设定项列表,但参数 没有指定从初始值设定项列表中扣除的类型。