Skip to content

Instantly share code, notes, and snippets.

@qrealka
Created August 1, 2019 17:28
Show Gist options
  • Save qrealka/ae32373eca4d3f966e820bbba82ab00a to your computer and use it in GitHub Desktop.
Save qrealka/ae32373eca4d3f966e820bbba82ab00a to your computer and use it in GitHub Desktop.
forward capture
// https://vittorioromeo.info/index/blog/capturing_perfectly_forwarded_objects_in_lambdas.html
#include <iostream>
#include <functional>
#define FWD(...) std::forward<decltype(__VA_ARGS__)>(__VA_ARGS__)
namespace impl
{
template <typename... Ts>
auto fwd_capture(Ts&&... xs)
{
return std::tuple<Ts...>(FWD(xs)...);
}
}
template <typename T>
decltype(auto) access(T&& x) { return std::get<0>(FWD(x)); }
#define FWD_CAPTURE(...) impl::fwd_capture(FWD(__VA_ARGS__))
struct A
{
int _value{0};
};
auto foo = [](auto&& a)
{
return [a = FWD_CAPTURE(a)]() mutable
{
++access(a)._value;
std::cout << access(a)._value << "\n";
};
};
int main()
{
{
auto l_inner = foo(A{});
l_inner(); // Prints `1`.
l_inner(); // Prints `2`.
l_inner(); // Prints `3`.
}
{
A my_a;
auto l_inner = foo(my_a);
l_inner(); // Prints `1`.
l_inner(); // Prints `2`.
l_inner(); // Prints `3`.
// Prints '3', yay!
std::cout << my_a._value << "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment