Skip to content

Instantly share code, notes, and snippets.

@indiosmo
Last active May 8, 2020 17:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save indiosmo/3f625d400f4243bfc28fbdc7d8039682 to your computer and use it in GitHub Desktop.
Save indiosmo/3f625d400f4243bfc28fbdc7d8039682 to your computer and use it in GitHub Desktop.
C++20 parameter pack perfect capture
#include <iostream>
#include <string>
template <class T, class...Args>
auto ftemplate(T& t) {
auto thunk = [&t](auto& f, Args&&... args) {
auto post = [&t, &f, ... args = std::forward<Args>(args)] {
f(t, std::forward<decltype(args)>(args)...);
};
return post;
};
return thunk;
}
auto fauto(int& t) {
auto thunk = [&t](auto& f, auto&&... args) {
auto post = [&t, &f, ... args = std::forward<decltype(args)>(args)] {
f(t, std::forward<decltype(args)>(args)...);
};
return post;
};
return thunk;
}
template<typename T>
auto ftemplate_auto(T& i) {
auto thunk = [&i](auto& f, auto&&... args) {
// this capture fails
auto post = [&f, ... args = std::forward<decltype(args)>(args)] {
f(std::forward<decltype(args)>(args)...);
};
return post;
};
return thunk;
}
int main(int, char**) {
int i=5;
auto f = [](auto&&... args) {
(std::cout << ... << std::forward<decltype(args)>(args)) << "\n";
};
auto t = ftemplate<int, int, int, std::string>(i);
t(f, 1, 4, "string")();
auto t2 = fauto(i);
t2(f, 2,5,"string")();
// comment this and it will build
auto t3 = ftemplate_auto(i);
t3(f, 2,5,"string")();
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment