Is it possible to access the captured values of a lambda outside of the lambda code itself.
template <typename F>
void bar(const F& f)
{
auto d = f.x;
}
int main()
{
int x;
bar([&]{
do_something(x);
});
}
This is not possible. The lambda is a black box.
If you need just one of the captured variable, and if the lambda was initially supposed to be void, then just return this value.
template <typename F>
void bar(const F& f)
{
auto d = f();
}
int main()
{
int x;
bar([&]{
auto y=x; // in case do_something would change x
do_something(x);
return y;
});
}
If you need already to return a value, you coud use the sam approach but use a pair or a tuple to return several values at once:
template <typename F>
void bar(const F& f)
{
auto d = f();
cout << d.first<<endl;
}
int main()
{
int x;
bar([&]{
auto y=x;
do_something(x);
return make_pair(y, 0); // first is parameter, second real return
});
}
Well it's not a lambda anymore. But if you need to access parameters of some more complex function, you could use a callable object. THe callable is a normal class or struct. It can then convey any parameters you want, but you need to defined them and foresee them in the constructor of the callable:
template <typename F>
void bar(const F& f)
{
auto d = f.x;
f();
}
int main()
{
struct Tmp { // I won't need this callable elsewhere...
int &x;
Tmp (int& x) : x(x) {}
void operator() () const {
do_something(x);
}
};
int x;
Tmp t(x);
bar(t);
}
In this example, I used a local class definition in order not to polute the namespace with throw-away struct.
You could combine this approach with the lambda by providing the lambda as parameter for the constructor, capturing a large number of variables, and use the callable members to convey onl the few you could use in bar()
.
Be caution with the capture by reference (not using the lambda when captured variables could heve deceased.
If you need to access named parameters of a lambda, there might be an issue in the design. Lambdas are not there to convey captured variables. So if you feel this need, there are chances that a callable could be a better option.
Is it possible to access the captured values of a lambda outside of the lambda code itself
Well, yes, but not via the lambda: somehow exposing all the local names captured by an [&]
lambda sounds pretty nasty.
Those variables already had names before they were bound to the lambda, and you can still use those names as normal.
Writing your own functor, with your own names and semantics, is the only way to get the behaviour you asked for. If you don't want to name every captured variable explicitly, you could use a tuple with std::apply
(and normal tuple field access) instead.
auto d = f()
x
yourself