Last active
May 8, 2020 17:49
-
-
Save indiosmo/3f625d400f4243bfc28fbdc7d8039682 to your computer and use it in GitHub Desktop.
C++20 parameter pack perfect capture
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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