-
Notifications
You must be signed in to change notification settings - Fork 269
Ability to decay capturing lambdas into plain functions with a context argument #1389
-
C++ has a feature where a lambda without a capture can decay into a regular function pointer:
int (*fn)() = []() -> int { return 1; };
It would be nice if capturing lambdas could decay to a regular function pointer taking a context argument:
auto [fn, ctx] = [a = 0](__Context &) -> int { return a; };
fn(ctx);
The way this can be done in cpp2 is with something like:
b: i32 = 2;
// The $ parameter signifies where the context argument gets passed to
(fn, ctx) := :(a: i32, ,ドル c: i32) -> int { return a + b$ + c; };
fn(1, ctx, 3);
cpp2 can translate this into:
struct Ctx_0 { i32 b; };
int fn_0(i32 a, void *vctx, i32 c) {
Ctx_0 *ctx = (Ctx_0*)vctx;
return a + ctx.b + c;
}
struct FnCtx_0 {
int (*fn)(i32, void *, i32);
Ctx_0 ctx;
};
auto [fn, ctx] = FnCtx_0 {
.fn = &fn_0,
.ctx = {
.b = 2
}
};
fn(1, ctx, 3);
Beta Was this translation helpful? Give feedback.
All reactions
Replies: 1 comment 2 replies
-
What's the benefit of this over the lambda being an object of some type with a regular operator()? What's the use case?
Beta Was this translation helpful? Give feedback.
All reactions
-
Compatibility with C APIs that take function pointers + context parameters for their callbacks.
Beta Was this translation helpful? Give feedback.
All reactions
-
Oh interesting. This is more general than lambdas though: I might want such a C API to call a regular C++ object method of mine. The "context" is the this pointer, like in the case of lambdas.
Beta Was this translation helpful? Give feedback.