Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Ability to decay capturing lambdas into plain functions with a context argument #1389

DerpMcDerp started this conversation in Suggestions
Discussion options

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);
You must be logged in to vote

Replies: 1 comment 2 replies

Comment options

What's the benefit of this over the lambda being an object of some type with a regular operator()? What's the use case?

You must be logged in to vote
2 replies
Comment options

Compatibility with C APIs that take function pointers + context parameters for their callbacks.

Comment options

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet

AltStyle によって変換されたページ (->オリジナル) /