tags:

views:

173

answers:

3

In c++0x is there a way to template a lambda function? Or is it inherently too specific to be templated?

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?

+2  A: 

In the current C++0x draft standard, it's not possible because lambdas are actually expressions, not function definitions. Expressions that happen to evaluate to unnamed temporary objects of unique type:

N3092, paragraph 15.1.2/3

The type of the lambda-expression (which is also the type of the closure object) is a unique, unnamed nonunion class type

Templates can only be applied to declarations and definitions, not expressions (per 14/1)

Cubbi
This doesn't mean anything. A lambda being an expression is just there for convenience. By your exact same argument, objects can't be defined in expressions so lambda's shouldn't be able to be functors. (In other words, polymorphic lambda's would change the definition of the unnamed temporary object it evaluates to. This has nothing to do with it being an expression.)
GMan
@GMan: I was looking at it from the *function template* side: for a lambda "function" to be a placed after the keyword template, it has to be a function definition, which it isn't. As for why closure objects weren't allowed to be polymorphic.. thanks for pointing towards the rationale behind that.
Cubbi
+7  A: 

At it stands, sadly no. Polymorphic lambda's 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
}

In a constrained template you can only call other contained 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)?

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 lambda's.

However, with the removal of concepts from C++0x, polymorphic lambda's become a simple proposition again. However, I can't find any proposals for it. :(

GMan
A: 

Have a look at Boost.Phoenix for polymorphic lambdas: http://www.boost.org/doc/libs/1_44_0/libs/spirit/phoenix/doc/html/index.html Does not require C++0x, by the way :)

usta
I already know about it but the question is exactly about the new standard anyway ;)
Klaim
Ok :) C++0x lambdas are monomorphic and can't be templated, unfortunately.
usta