问题描述
在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?
推荐答案
UPDATE 2014:C ++ 14今年已经发布,现在提供多态lambdas相同的语法比本例中。一些主要的编译器已经实现了它。
UPDATE 2014: C++14 have been released this year and now provide Polymorphic lambdas with the same syntax than in this example. Some major compilers already implements it.
在C ++ 11中,可悲的是没有。多态性lambdas在灵活性和力量方面将是非常好的。
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
invoke bar(x)
?
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
(其中的概念没有选中,直到调用)和东西。更简单的只是放弃所有的并坚持单态lambdas。
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删除概念,多态lambdas成为一个简单的命题。但是,我找不到任何建议。 :(
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函数可以模板化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!