Get captured variables from lambda?

By : Skeen

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.

By : Skeen

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.

No. C++ has no reflection, and that means it doesn't have reflection on lambda's either.

By : MSalters

This video can help you solving your question :)
By: admin