问题描述
在 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 函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!