Can lambda functions be templated?(可以模板化 lambda 函数吗?)
问题描述
在 C++11 中,有没有办法模板化 lambda 函数?或者它天生就太具体而无法模板化?
In C++11, is there a way to template a lambda function? Or is it inherently too specific to be templated?
我知道我可以定义一个经典的模板化类/函子,但问题更像是:该语言是否允许模板化 lambda 函数?
I understand that I can define a classic templated class/functor instead, but the question is more like: does the language allow templating lambda functions?
推荐答案
2018 年更新:C++20 将带有模板化和概念化的 lambdas.该功能已集成到标准草案中.
UPDATE 2018: C++20 will come with templated and conceptualized lambdas. The feature has already been integrated into the standard draft.
2014 年更新:C++14 已于今年发布,现在提供了与本示例中语法相同的多态 lambda.一些主要的编译器已经实现了它.
UPDATE 2014: C++14 has been released this year and now provides Polymorphic lambdas with the same syntax as in this example. Some major compilers already implement it.
目前(在 C++11 中),遗憾的是没有.多态 lambda 在灵活性和功能方面会非常出色.
At it stands (in C++11), sadly no. Polymorphic lambdas would be excellent in terms of flexibility and power.
它们最终成为单态的最初原因是因为概念.概念使这种代码情况变得困难:
The original reason they ended up being monomorphic was because of concepts. Concepts made this code situation difficult:
template <Constraint T>
void foo(T x)
{
auto bar = [](auto x){}; // imaginary syntax
}
在受约束的模板中,您只能调用其他受约束的模板.(否则无法检查约束.) foo
可以调用 bar(x)
吗?lambda 有什么约束(毕竟它的参数只是一个模板)?
In a constrained template you can only call other constrained templates. (Otherwise the constraints couldn't be checked.) Can foo
invoke bar(x)
? What constraints does the lambda have (the parameter for it is just a template, after all)?
概念还没有准备好解决这类问题;它需要更多的东西,比如 late_check
(在调用之前不检查概念)和其他东西.更简单的方法是放弃所有内容并坚持使用单态 lambda.
Concepts weren't ready to tackle this sort of thing; it'd require more stuff like late_check
(where the concept wasn't checked until invoked) and stuff. Simpler was just to drop it all and stick to monomorphic lambdas.
然而,随着 C++0x 中概念的删除,多态 lambda 再次成为一个简单的命题.但是,我找不到任何建议.:(
However, with the removal of concepts from C++0x, polymorphic lambdas become a simple proposition again. However, I can't find any proposals for it. :(
这篇关于可以模板化 lambda 函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:可以模板化 lambda 函数吗?


基础教程推荐
- 管理共享内存应该分配多少内存?(助推) 2022-12-07
- 如何“在 Finder 中显示"或“在资源管理器中显 2021-01-01
- 为 C/C++ 中的项目的 makefile 生成依赖项 2022-01-01
- 使用从字符串中提取的参数调用函数 2022-01-01
- 如何使图像调整大小以在 Qt 中缩放? 2021-01-01
- 如何在不破坏 vtbl 的情况下做相当于 memset(this, ...) 的操作? 2022-01-01
- Windows Media Foundation 录制音频 2021-01-01
- 在 C++ 中循环遍历所有 Lua 全局变量 2021-01-01
- 为什么语句不能出现在命名空间范围内? 2021-01-01
- 从 std::cin 读取密码 2021-01-01