Skip to content

Instantly share code, notes, and snippets.

@oliora
Last active May 18, 2018 06:26
Show Gist options
  • Save oliora/b26a8366cbbc6086e8ec5ea8a65b80d0 to your computer and use it in GitHub Desktop.
Save oliora/b26a8366cbbc6086e8ec5ea8a65b80d0 to your computer and use it in GitHub Desktop.
make_handle
// version 1.0
template<class T, class D>
inline auto make_handle(T* p, D&& d) noexcept(std::is_nothrow_constructible<typename std::decay<D>::type, D&&>::value)
-> std::unique_ptr<T, typename std::decay<D>::type>
{
return {p, std::forward<D>(d)};
}
auto h1 = make_handle(fopen("test", "r"), fclose);
auto h2 = make_handle(dlopen("bla"), dlclose);
// Lambda is fine as well:
auto h3 = make_handle(dlopen("bla"), [](void *p) { dlclose(p); });
// Capturing lambda is fine as well
auto h4 = make_handle(fopen("test", "r"), [&](FILE *f) {
...
fclose(f);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment