Converting Lambdas to Function Pointers

ISO/IEC JTC1 SC22 WG21 N3043 = 10-0033 - 2010-02-15

Lawrence Crowl,,
Alisdair Meredith,

This paper extracts a generally uncontroversial portion of N2989 = 09-0179.


The semantics of a lambda with an empty capture list and a function are nearly uniform. This uniformity was noted in U.K. national body comment 226. Exposing this uniformity would allow programmers to use lambdas and exploit existing function-based interfaces.

Problem: A lambda with an empty capture list has identical semantics to a regular function type. By requiring this mapping we get an efficient lambda type with a known API that is also compatible with existing operating system and C library functions.

Resolution: Add a new paragraph: "A lambda expression with an empty capture set shall be convertible to pointer to function type R(P), where R is the return type and P is the parameter-type-list of the lambda expression." Additionally it might be good to (a) allow conversion to function reference and (b) allow extern "C" function pointer types.

We adopt the suggested resolution.

Proposed Wording

The proposed wording shows changes from working draft N3000.

5.1.2 Lambda expressions [expr.prim.lambda]

Edit paragraph 5 as follows. The intent of this edit is to obtain a closure-to-function-pointer conversion with no lambda-capture.

The closure type for a lambda-expression has a public inline function call operator (13.5.4) whose parameters and return type are described by the lambda-expression's parameter-declaration-clause and trailing-return-type respectively. A program taking the address of this function call operator is ill-formed. This function call operator is declared const (9.3.1) if and only if the lambda-expression's parameter-declaration-clause is not followed by mutable. It is not declared volatile. Default arguments (8.3.6) shall not be specified in the parameter-declaration-clause of a lambda-declarator. Any exception-specification specified on a lambda-expression applies to the corresponding function call operator. Any attribute-specifiers appearing immediately after the lambda-expression's parameter-declaration-clause appertain to the type of the corresponding function call operator. [Note: Names referenced in the lambda-declarator are looked up in the context in which the lambda-expression appears. —end note]

Add a new paragraph after paragraph 5.

The closure type for a lambda-expression with no lambda-capture has a public non-virtual non-explicit const conversion function to pointer to function having the same parameter and return types as the closure type's function call operator. The value returned by this conversion function shall be the address of a function that, when invoked, has the same effect as invoking the closure type's function call operator.