Reputation: 47658
I want to create lambda that will accept any number of arguments like:
template <typename... Args>
void f(Args... args) {
auto l = [args...]() {
g(args...);
}
// use l
}
Problem here is that it doesn't work with move-only types. If it was only 1 arg I would do smth like
void f(Arg arg) {
auto l = [arg = std::move(arg)]() {
g(move(arg));
}
}
How to move all args to lambda?
Upvotes: 9
Views: 900
Reputation: 275878
template <class... Args>
void f(Args... args) {
auto l = [tup=std::make_tuple(std::move(args)...)] {
std::apply([](auto&&...args){
g(decltype(args)(args)...);
}, tup );
};
}
A bit icky.
Pack them into a tuple, then unpack tuple with std::apply
. If you lack std::apply
write yourself an equivalent one.
If you want to invoke g
with rvalues, make outer lambda mutable, and move
tuple into inner lambda.
Inner lambda can capture by default &
if you want access to args of outer or the like.
We can even abstract this pattern a bit:
template<class F, class...Args>
auto forward_capture( F&& f, Args&&...args ) {
return [
f=std::forward<F>(f),
tup=std::make_tuple(std::forward<Args>(args)...)
]{
return std::apply( f, tup );
};
}
use:
template <typename... Args>
void f(Args... args) {
auto l = forward_capture(
[](auto&&...args) {
g(args...);
},
std::move(args)...
);
// use l
}
If you want the capture list first, we can do it:
template<class...Args>
auto forward_capture( Args&&...args ) {
return [
tup=std::make_tuple(std::forward<Args>(args)...)
](auto&& f)mutable{
return [
f=decltype(f)(f),
tup=std::move(tup)
]{
return std::apply( f, tup );
};
};
}
use:
template <typename... Args>
void f(Args... args) {
auto l = forward_capture(std::move(args)...)(
[](auto&&...args) {
g(args...);
}
);
// use l
}
which has the "advantage" that we have 3 nested lambdas.
Or more fun:
template<class...Args>
struct arrow_star {
std::tuple<Args...> args;
template<class F>
auto operator->*(F&& f)&& {
return [f=std::forward<F>(f),args=std::move(args)]()mutable{
return std::experimental::apply( std::move(f), std::move(args) );
};
}
};
template<class...Args>
arrow_star<std::decay_t<Args>...> forward_capture( Args&&...args ) {
return {std::make_tuple(std::forward<Args>(args)...)};
}
template<class...Args>
auto f(Args... args)
{
return
forward_capture( std::move(args)... )
->*
[](auto&&...args){
g(decltype(args)(args)...);
};
}
Upvotes: 8