使用 std::function 调用函数作为带有 lambda 的参数
Call a function with std::function as argument with a lambda
我从这里得到的问题的基础: 无法从 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)>
成为一个非推导的上下文。因此,对于第一个参数,演绎不能再失败,因为它甚至没有尝试过。因此,仅从第二个参数推断出T
int
,并且调用成功,因为 lambda 可转换为std::function<void(int)>
。
从 [温度扣除类型]:
非推导上下文是:
- 。
- 一个函数参数,其关联参数是初始值设定项列表,但参数 没有指定从初始值设定项列表中扣除的类型。
相关文章:
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 使用自动推导的 lambda 参数作为常量表达式
- 如何参数化用作另一个 lambda 参数的 lambda
- 有没有办法根据 lambda 参数返回类型部分专用化我的模板化函数?
- 从成员函数签名中自动推导lambda参数
- Clang声称通用lambda参数的constexpr成员不是constexpr
- 如果我的模板类型首先以lambda参数而发生,则MSVC会引起一个奇怪的错误
- 继承类中没有匹配的泛型委托作为 lambda 参数
- 为什么在lambda参数中不允许自动
- 如何定义通用 lambda 参数的模板参数?
- 在 QGraphicsScene 中拖动 QPixmap:如何避免 lambda 参数中不允许'auto'
- variadic模板函数会以相反的顺序调用lambda参数
- 可变模板lambda参数的模板推导
- 嵌套模板功能中的C 0x lambda参数
- 带有 std::函数和 lambda 参数的分段错误
- 从值捕获的变量分配到lambda参数时,GCC编译器分割故障
- 标准::p空气的通用 lambda 参数
- C++ lambda 参数列表
- 我的 lambda 参数真的在阴影我的当地人吗?
- 从常量和引用的角度来看,函数应该如何接受*lambda*参数