使用模板将 lambda 解析为函数
Parsing lambda to a function using templates
我对C++很陌生,我目前正在尝试学习如何将模板用于lambda函数。
lambda 可以在 main
函数中看到,它只是进行布尔检查。
下面的实现有效,但我必须在 testing
函数中显式声明 lambda 的类型,如输入参数所示。
void testing(std::function<bool(const int& x)> predicate){
auto a = predicate(2);
std::cout << a << "n";
}
int main() {
int ax = 2;
testing([&ax](const int& x) { return x == ax;});
}
我希望有一个可以实现,我可以利用如下所示的模板,但我无法获得任何工作。
template <typename T>
void testing(std::function<bool(const T& x)> predicate){
auto a = predicate(2);
std::cout << a << "n";
}
有没有一种通用的方法可以使用 lambda 模板?
不要将模板参数包装在 std::function
中。
将 lambda 传递给函数的最佳方法是将其作为不受约束的模板参数:
template<class F>
void testing(F predicate) {
auto a = predicate(2);
std::cout << a << 'n';
}
int main() {
int ax = 2;
testing([ax](int x) { return x == ax; });
}
好处超过std::function
.
-
std::function
在堆上分配空间来存储函子 -
std::function
具有类似于虚函数调用的开销 - 编译器不能内联
std::function
,但内联直接传递的 lambda 是微不足道的
相关文章:
- 可组合的lambda/std::函数与std::可选
- C++Boost Asio Pool线程,带有lambda函数和传递引用变量
- 如何建立使用模板函数的lambda函数的尾部返回类型
- 如何将lambda作为模板类的成员函数参数
- 我可以将调用类的"this"传递给 lambda 函数吗?
- 模板函数指针和lambda
- 两组使用lambda函数的大括号
- 尝试将lambda函数放在队列中时出现一般分配器错误(可能是与unique_ptr有关的错误)
- 我可以在这里替换什么,因为我不能在 C# 中使用隐式变量的 lambda 函数?
- 在构造函数中使用 lambda 的 C++ 类
- 如何调用存储在指向"std::函数"的指针中的 lambda?
- 为什么我不能在 constexpr lambda 函数中使用 std::tuple
- 从具有按值捕获的 lambda 移动构造 std::函数时,移动构造函数调用两次
- C++:Lambda 函数指针转换的用例是什么?
- 将有状态的 lambda 传递到 C 样式函数中,而无需上下文参数
- std::映射服装比较函数和函数/lambda错误
- 在可移动类型的构造函数 lambda 中捕获此内容的安全使用
- 排序测试模板化函数 lambda:非法使用此类型作为表达式
- 将匿名函数(lambda)保存为函数类型变量
- 如何编写将自身作为回调传递的匿名函数/lambda