Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get captured variables from lambda?

I was wondering, if there's a way to get the types/values of the captured variables of a lambda? - The usage scenario would be something alike;

int a = 5;
auto lamb = [a](){ return a; };
static_assert(std::is_same<typename get_capture_type<0>(lamb)::type, int>::value, "");
assert(get_capture_value<0>(lamb) == 5)

Note: get_capture_*<N>(lambda) should obviously result in a compiler error, when N > #captured_variables.

What I need is actually just a way to access the captures somehow, if possible. That is, I can do the template meta-programming myself.

like image 397
Skeen Avatar asked Nov 13 '13 19:11

Skeen


1 Answers

It's not possible by design

5.1.2 [expr.prim.lambda]
15 [...] For each entity captured by copy, an unnamed non-static data member is declared in the closure type. The declaration order of these members is unspecified. [...]
16 [...] It is unspecified whether additional unnamed non-static data members are declared in the closure type for entities captured by reference.

Captured variables are unnamed (or at least have names that are unspeakable by mortals) and their declaration order is deliberately unspecified. By-reference captures may not even exist in the closure type.

You don't want to do this anyway. You may think you do, but you don't really.

like image 175
Jonathan Wakely Avatar answered Oct 04 '22 01:10

Jonathan Wakely