Skeen
Skeen

Reputation: 4722

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.

Upvotes: 8

Views: 692

Answers (3)

Gabriel
Gabriel

Reputation: 3077

As mentioned in other answers, this might not be possible because lambda fields are unnamed.

You could write your own function object, though. A struct with the fields you'd capture and an operator().

In your case, i suspect the following would work:

#include <cassert>
#include <type_traits>

struct mylambda {
    int a;
    int operator()() { return a; }
};

int main()
{
    int a = 5;
    auto lamb = mylambda{a};
    static_assert(std::is_same<decltype(lamb.a), int>::value, "");
    assert(lamb.a == 5);
    return 0;
}

Upvotes: 0

Jonathan Wakely
Jonathan Wakely

Reputation: 171263

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.

Upvotes: 16

MSalters
MSalters

Reputation: 179779

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

Upvotes: 5

Related Questions